温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - How do I replace deprecated crypto.createCipher in nodejs?
encryption node.js

node.js - 如何替换Node.js中已弃用的crypto.createCipher?

发布于 2020-05-17 23:03:12

我正在使用以下功能来加密/解密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.

如何重写此代码以升级源代码?

查看更多

提问者
Stepan Yakovenko
被浏览
946
Zeeshan Hassan Memon 2020-02-24 18:10

因此,我们可以这样说:

将过时的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