3

My client side code:

data.username = CryptoJS.AES.encrypt(user.username, "password");
data.password = CryptoJS.AES.encrypt(user.password, "password");

Then I am sending 'data' to server which is express.js

var user = req.body;
var decipher = crypto.createDecipher('aes256', "password");
var decrypted = decipher.update(user.username, 'hex', 'utf-8');
decrypted += decipher.final('utf-8'); 

I am getting this error:

Error: DecipherInit error
at new Decipher (crypto.js:368:17)
at Object.Decipher (crypto.js:365:12)
Mmohits
  • 201
  • 1
  • 2
  • 10
  • Here are some similar questions and answers: [Decrypting AES256 with node.js returns wrong final block length](https://stackoverflow.com/q/21292142/608639), [Nodejs decrypt using crypto error wrong final block length](https://stackoverflow.com/q/23111388/608639), [Getting error wrong final block length while decrypting AES256](https://stackoverflow.com/q/32038267/608639), [Decrypt file in Node.js encrypted using OpenSSL](https://stackoverflow.com/q/44482151/608639), [What's wrong with node.js crypto decipher?](https://stackoverflow.com/q/12219499/608639) – jww Jun 11 '17 at 10:19

1 Answers1

0

CryptoJS' encrypt function with a password uses the same EVP_BytesToKey function node.js' createCipher, with the important difference that CryptoJS uses a random salt to derive whereas node does not (emphasis mine):

Note: createCipher derives keys with the OpenSSL function EVP_BytesToKey with the digest algorithm set to MD5, one iteration, and no salt.

Either you directly use CryptoJS in node which is possible, because CryptoJS doesn't have any dependencies, or you do the key derivation yourself on both ends and use crypto.createCipheriv. If you do the former, you would have to additionally pass the salts of the username and password encryptions to node.

Note that data.username is the CryptoJS cipherParams object which contains the salt and the IV, but when you convert this to string with data.username.toString(), the salt is not included anymore, but the IV is. This is not the data that you would put into the node.js functions. Send data.username.ciphertext instead.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 1
    [OpenSSL 1.1.0c changed the digest algorithm](http://stackoverflow.com/q/39637388/608639) used in some internal components. Formerly, MD5 was used, and 1.1.0 switched to SHA256. Be careful the change is not affecting you in both `EVP_BytesToKey` and commands like `openssl enc`. – jww Jan 26 '17 at 16:30