Anomaly211
Anomaly211

Reputation: 1103

Invalid Key Length After Upgrading to NodeJS 6

The following Code to encrypt and decrypt requests to our payment gateway service 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 has always been 16 characters (i.e 128 bits) and was working before the upgrade. Why would this problem be happening now?

Upvotes: 10

Views: 5109

Answers (1)

Anomaly211
Anomaly211

Reputation: 1103

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

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

The fixed code reads as

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;
};

My thanks to @Artjom-b for the answer.

Upvotes: 14

Related Questions