Support for both crypto.createCipher
& crypto.createDecipher
has been pulled as they use a weak key derivation function (MD5 with no salt) and static initialization vectors (iv).
Here, we'll work with migrating from crypto.createCipher
& crypto.createDecipher' to
crypto.createCipheriv&
crypto.createDecipheriv`
Let's begin with the basics. Run the following command in parent directory of your node.js project.
npm install crypto --save
Encryption
Make sure that the secret key & secret initialization vector is set correctly with required length. To keep the format intact we use createHash
from crypto.
Here is the code below:
var Crypto = require('crypto')
var secret_key = 'fd85b494-aaaa'
var secret_iv = 'smslt'
var encryptMethod = 'AES-256-CBC';
var key = Crypto.createHash('sha512').update(secret_key, 'utf-8').digest('hex').substr(0, 32);
var iv = Crypto.createHash('sha512').update(secret_iv, 'utf-8').digest('hex').substr(0, 16);
var encryptMsg = encryptStr("Encrypting", encryptMethod, key, iv);
console.log(encryptedMsg);
function encryptStr(plain_text, encryptMethod, secret, iv) {
var encryptor = Crypto.createCipheriv(encryptMethod, secret, iv);
var aes_encrypted = encryptor.update(plain_text, 'utf8',
'base64') + encryptor.final('base64');
return Buffer.from(aes_encrypted).toString('base64');
};
Decryption
Here is the code below:
var Crypto = require('crypto');
var secret_key = 'fd85b494-aaaa';
var secret_iv = 'smslt';
var encryptMethod = 'AES-256-CBC';
var decryptMessage = decryptStr(encryptText, encryptionMethod, key , iv);
console.log(decrptMessage);
function decryptStr(encryptText, encryptMethod, secret, iv) {
const buff = Buffer.from(encryptText, 'base64');
encryptedMessage = buff.toString('utf-8');
var decryptor = Crypto.createDecipheriv(encryptMethod, secret, iv);
return decryptor.update(encryptText, 'base64', 'utf8') + decryptor.final('utf8');
};
References:
Crypto|Node.js v20.2.0 Documentation
Top comments (0)