Invalid key length after upgrading to NodeJS 6

The following code to encrypt and decrypt requests to our payment gateway works correctly with Node Js 5.7.0

function Encrypt(plainText, workingKey) { var m = crypto.createHash('md5'); m.update(workingKey); var key = m.digest('binary'); var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'; var cipher = crypto.createCipheriv('aes-128-cbc', key, iv); var encoded = cipher.update(plainText, 'utf8', 'hex'); encoded += cipher.final('hex'); return encoded; }; function Decrypt(encText, workingKey) { var m = crypto.createHash('md5'); m.update(workingKey) var key = m.digest('binary'); var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'; var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv); var decoded = decipher.update(encText, 'hex', 'utf8'); decoded += decipher.final('utf8'); return decoded; }; 

However, after upgrading to NodeJS 6.0 (also tried 6.1), we get the following error.

 Debug: internal, implementation, error Error: Uncaught error: Invalid key length at Error (native) at new Cipheriv (crypto.js:184:16) at Object.Cipheriv (crypto.js:182:12) 

Our key length was always 16 characters (i.e. 128 bits) and worked until the update. Why will this problem be now?

+7
cryptography encryption
source share
1 answer

I am posting the answer here in the hope that it can help someone.

The problem seems to be caused by using a binary digest for the key. The solution is to simply call the digest function and instead save the key as a buffer.

Fixed code reads like

 function Encrypt(plainText, workingKey) { var m = crypto.createHash('md5'); m.update(workingKey); var key = m.digest(); var iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'; var cipher = crypto.createCipheriv('aes-128-cbc', key, iv); var encoded = cipher.update(plainText, 'utf8', 'hex'); encoded += cipher.final('hex'); return encoded; }; 

I thank @ Artjom-b for the answer.

+7
source share

All Articles