我正在 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
我相信bad decrypt
意味着 openssl 不理解加密密钥
这是发生的事情。
crypto
使用提供的密码和盐生成加密密钥:crypto.scrypt(password, 'salt', 32,...
crypto.randomFill(new Uint8Array(16)
pipeline(input, cipher, output,
因此,要使用 openssl 解密此文件,需要提供密钥和 iv。
这是解密它的一种方法。请参阅底部添加的生成 openssl 解密命令的代码:
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;
}
});
// Generate openssl decrypt command
const hexKey = key.toString('hex');
const hexIv = Buffer.from(iv).toString('hex');
console.log(`openssl enc -aes-256-cbc -d -in test.enc -out test2.txt -K ${hexKey} -iv ${hexIv}`);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句