Search code examples
node.jsencryptioncryptographycryptojsdiffie-hellman

How to make Diffie Hellman connection between client(CryptoJS) and server(Crypto Node.js)


I'm trying to make connection between server and client. I create ECDH keys with elliptic.js and try to cipher-decipher messages. Secret keys are equal both on server and on client. Between servers everything is ok, but between server and client there are a lot of problems.

I have worked a lot to make the client to decipher messages from server. But I can't make right ciphering on client. Server doesn't understand it. Even the client doesn't understand it.

My client uses Crypto JS (I tried to use forge and sjcl but they was much herder for me to understand) and server uses Crypto. There are my functions on client:

cipherData(data, secret){       
  let encrypted = CryptoJS.AES.encrypt(data, secret).toString();
  return encrypted;
}

decipherData(encryptedData, secret) {
  let data;
  try {
      //make tranformations because of little features in crypto (node) - it uses empty salt array
      let ct = CryptoJS.enc.Hex.parse(encryptedData);
      let salt = CryptoJS.lib.WordArray.create(0); // empty array
      data = CryptoJS.AES.decrypt({ciphertext: ct, salt: salt}, secret);
      data = data.toString(CryptoJS.enc.Utf8);
  } catch (e) {
      console.log('Error decrypting data: ' + e)
  }
  return data;
}

There is my code on server:

cipherData(data, secret, algorithm = 'aes256'){
  const cipher = crypto.createCipher(algorithm, secret);
  let encrypted = cipher.update(data,'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

decipherData(encryptedData, secret, algorithm = 'aes256'){
  const decipher = crypto.createDecipher(algorithm, secret);
  let data = decipher.update(encryptedData,'hex', 'utf8');
  data += decipher.final('utf8');
  return data;
}

Maybe someone could help me? Computed secret key for example(in hex): e6922091e78adce7cff10e01b4eb949317e56ece3597a7daa23c819c6882a955


Solution

  • After many attempts I desided to remake server-side using Crypto-JS too. That decision was completely right. All working fine.

        cipherData(data, secret) {
            let encrypted = CryptoJS.AES.encrypt(data, secret).toString();
            let b64 = CryptoJS.enc.Base64.parse(encrypted);
            encrypted = b64.toString(CryptoJS.enc.Hex);
            return encrypted;
        }
    
        decipherData(encryptedData, secret) {
            let data;
            try {
                let b64 = CryptoJS.enc.Hex.parse(encryptedData);
                let bytes = b64.toString(CryptoJS.enc.Base64);
                data = CryptoJS.AES.decrypt(bytes, secret);
                data = data.toString(CryptoJS.enc.Utf8);
            } catch (e) {
                console.log('Error decrypting data: ' + e)
            }
            return data;
        }