Search code examples
node.jsencryption

How do I replace deprecated crypto.createCipher in Node.js?


I am using following functions to encrypt/decrypt strings in Node.js:

var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
function encrypt(text) {
    var cipher = crypto.createCipher(algorithm, password);
    try {
        var crypted = cipher.update(text, 'utf8', 'hex');
        crypted += cipher.final('hex');
    } catch (e) {
        return;
    }
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(algorithm, password);
    try {
        var dec = decipher.update(text, 'hex', 'utf8');
        dec += decipher.final('utf8');
    } catch (e) {
        return;
    }
    return dec;
}

(password is stored separately from encoded text). New version of nodejs/crypt package complains:

(node:5212) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.

How do I rewrite this to upgrade my source code?


Solution

  • So lets say it like:

    Replace deprecated crypto.createDecipher usage with crypto.createDecipheriv

    why? because:

    according to the deprecation docs it was due to security concerns.

    Using crypto.createCipher() and crypto.createDecipher() should be avoided as they use a weak key derivation function (MD5 with no salt) and static initialization vectors. It is recommended to derive a key using crypto.pbkdf2() or crypto.scrypt() and to use crypto.createCipheriv() and crypto.createDecipheriv() to obtain the Cipher and Decipher objects respectively.

    Link to the above reference: Click Here

    Someone also said:

    As per crypto_crypto_createdecipher_algorithm_password_options, one now need to switch to crypto.createDecipheriv.

    Sample Code:

    const crypto = require('crypto');
    const algorithm = 'aes-256-ctr';
    const ENCRYPTION_KEY = 'Put_Your_Password_Here'; // or generate sample key Buffer.from('FoCKvdLslUuB4y3EZlKate7XGottHski1LmyqJHvUhs=', 'base64');
    const IV_LENGTH = 16;
    
    function encrypt(text) {
        let iv = crypto.randomBytes(IV_LENGTH);
        let cipher = crypto.createCipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return iv.toString('hex') + ':' + encrypted.toString('hex');
    }
    
    function decrypt(text) {
        let textParts = text.split(':');
        let iv = Buffer.from(textParts.shift(), 'hex');
        let encryptedText = Buffer.from(textParts.join(':'), 'hex');
        let decipher = crypto.createDecipheriv(algorithm, Buffer.from(ENCRYPTION_KEY, 'hex'), iv);
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        return decrypted.toString();
    }
    

    For complete running example clone node-cheat and run node crypto-create-cipheriv.js.