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

标签 node.js encryption

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

相关文章:

javascript - 在记录 Action 中变得空虚 - twilio

javascript - Mongoose 没有将更新的文档保存到数据库

android - 在使用 OpenSSL enc 子命令加密的 Android 上解密文件

时间:2019-03-17 标签:c#filecontainer

ssl - 握手失败(40)和 TLS_EMPTY_RENEGOTIATION_INFO_SCSV

node.js - Electron 快速入门拒绝连接到 'https://oauth2.googleapis.com/token'

javascript - React 组件未在 DOM 上渲染

java - Java中AES的解密

python - 如何在Python中找到pow(a,b,c)的逆序?

javascript - 使用 Node 导入 typescript