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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…