node.js - 使用 openssl 从加密模块解密文件

标签 node.js openssl cryptography cryptojs

我有一个用例,我们使用简单的 NodeJS 应用程序将日志数据流式传输到文件。我们希望能够在传输数据时对其进行加密,然后根据需要使用 OpenSSL 或类似工具对其进行解密。

我们正在做的事情基本上如下:

var crypto = require('crypto'),
        algorithm = 'aes256',
        password = 'password';

var fs = require('fs');

var Readable = require('stream').Readable

var r = new Readable
r.push('This is a test')
r.push(null)

var encrypt = crypto.createCipher(algorithm, password);
var decrypt = crypto.createDecipher(algorithm, password)

var w = fs.createWriteStream('file.out');

//Write encrypted stream to file. Decrypt with openssl fails with 'bad magic number'
r.pipe(encrypt).pipe(w)
//Decrypt using cipher library. Decrypted text displays as expected
//r.pipe(encrypt).pipe(decrypt).pipe(w)

假设我们只是在读取数据时对其进行加密,我假设我们可以使用开放的 OpenSSL 来解密它,例如

openssl enc -d -aes256 -in file.out -out file.out.decrypted

但这只是给了我错误

Bad magic number

任何帮助将不胜感激。

最佳答案

查看 crypto.createCipher() 的文档函数,它提到 OpenSSL EVP_BytesToKey()函数用于从密码短语中派生 key ,就像 openssl enc 一样应用程序确实如此。所以这看起来很兼容。

但是,同一文档没有提到应用了任何盐,并且该函数似乎也无法将盐作为参数传递。因此,您必须将 -nosalt 选项传递给 openssl enc 才能使其正常工作,如下所示:

openssl enc -d -aes256 -nosalt -in file.out -out file.out.decrypted

您可以仅使用 openssl enc 工具来模拟正在发生的情况,无论解密端是否有盐:

您目前的情况:

$ echo -n 'This is a test' | openssl enc -aes256 -nosalt -pass pass:password | openssl enc -d -aes256 -pass pass:password
bad magic number

解密时添加-nosalt:

$ echo -n 'This is a test' | openssl enc -aes256 -nosalt -pass pass:password | openssl enc -d -aes256 -nosalt -pass pass:password
This is a test

关于node.js - 使用 openssl 从加密模块解密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51385777/

相关文章:

node.js - 在 Node 中存储 mongoDB 的收集结果

apache - 如何将我的 SSL 证书从 Tomcat 移动到 Apache

c++ - QT C++ - OpenSSL AES - EVP.h

python-3.x - python中的uuid4和secrets token_bytes有什么区别?

java - Debian 上策略文件的位置

javascript - 在javascript中计算iso时间格式的时差?

node.js - 如何设置 mongoose 等待 mongodb 连接的最长时间

node.js - 如何避免 node.js TLS 模块中的 SELF_SIGNED_CERT_IN_CHAIN 错误?

javascript - 使用 AES key 包装 RSA 私钥然后解包

javascript - 在node.js中,如何将模块的所有事件转发给另一个