【发布时间】:2020-11-29 15:29:42
【问题描述】:
我正在加密 Node.js 中的文件,并尝试使用 OpenSSL 命令行进行解密。我是一位经验丰富的开发人员,但我没有完全接受过加密方面的教育。我基本上只需要一种以编程方式加密文件的好方法,并能够在以后使用命令行对其进行解密。
Node.JS 代码:
const crypto = require('crypto');
const fs = require('fs');
const { pipeline } = require('stream');
const algorithm = 'aes-256-cbc';
const password = 'ABC123';
crypto.scrypt(password, 'salt', 32, (err, key) => {
if (err) throw err;
// Then, we'll generate a random initialization vector
crypto.randomFill(new Uint8Array(16), (err, iv) => {
if (err) throw err;
const cipher = crypto.createCipheriv(algorithm, key, iv);
const input = fs.createReadStream('test.txt');
const output = fs.createWriteStream('test.enc');
pipeline(input, cipher, output, (err) => {
if (err) throw err;
});
});
});
我的 CLI 命令:
openssl enc -aes-256-cbc -nosalt -d -in test.enc -out test2.txt
这给了我:
bad decrypt
【问题讨论】:
-
代码不兼容。 OpenSSL 语句使用
EVP_BytesToKey()作为密钥和IV(无盐)的密钥派生函数(KDF),如果真的以这种方式进行加密,这将是非常不安全的。 NodeJS 代码将 scrypt 作为 KDF 用于密钥(带盐)和随机生成的 IV。为了兼容性,您必须使用相同的 KDF 和逻辑。
标签: node.js encryption openssl cryptojs