我正在使用以下函数来加密/解密 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;
}
(密码与编码文本分开存储)。新版本的nodejs/crypt包提示:
(node:5212) [DEP0106] DeprecationWarning: crypto.createDecipher is deprecated.
如何重写它来升级我的源代码?
最佳答案
所以我们可以这么说:
将已弃用的 crypto.createDecipher
用法替换为 crypto.createDecipheriv
为什么?因为:
根据deprecation文档称这是出于安全考虑。
应避免使用crypto.createCipher()
和crypto.createDecipher()
,因为它们使用弱 key 派生函数(无盐MD5)并且静态初始化向量。建议使用 crypto.pbkdf2()
或 crypto.scrypt()
派生 key ,并使用 crypto.createCipheriv()
和 crypto.createDecipheriv()
分别获取Cipher和Decipher对象。
以上引用链接:Click Here
还有人说:
根据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
。
关于node.js - 如何替换 Node.js 中已弃用的 crypto.createCipher?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60369148/