我正在使用以下功能来加密/解密nodejs中的字符串:
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;
}
(密码与编码的文字分开存储)。新版本的nodejs / crypt软件包抱怨:
(node:5212) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.
如何重写此代码以升级源代码?
因此,我们可以这样说:
将过时的crypto.createDecipher
用法替换为crypto.createDecipheriv
为什么?因为:
根据弃用文档,这是出于安全考虑。
使用crypto.createCipher()
和crypto.createDecipher()
应该避免使用,因为它们使用弱密钥派生函数(无盐的MD5)和静态初始化向量。建议使用crypto.pbkdf2()
或crypto.scrypt()
和导出密钥,并分别使用crypto.createCipheriv()
和crypto.createDecipheriv()
获取Cipher和Decipher对象。
链接到上述参考:单击此处
有人还说:
按照crypto_crypto_createdecipher_algorithm_password_options的要求,现在需要切换到crypto.createDecipheriv
。
样例代码:
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();
}
对于完整的运行示例,请克隆node-cheat并运行node crypto-create-cipheriv.js
。
如何重做我的代码的代码示例将很酷
好的,现在查看更新的答案,它同时具有代码和节点作弊链接。@StepanYakovenko