【问题标题】:Decrypting file from crypto module using openssl使用 openssl 从加密模块解密文件
【发布时间】:2018-12-25 09:57:51
【问题描述】:

我有一个用例,我们使用简单的 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

任何帮助将不胜感激。

【问题讨论】:

    标签: node.js openssl cryptography cryptojs


    【解决方案1】:

    默认情况下,OpenSSL 加密文件格式以 8 字节“幻数”开头,US-ASCII 编码为"Salted__"。随后是另一个 8 字节值,该值与密码一起用于派生消息的加密密钥和 IV。您的 NodeJS 代码没有以相同的方式派生密钥或提供必要的标头,因此它不起作用。

    OpenSSL 的密钥派生算法不安全且不标准。如果您自己使用 good 密钥派生算法(如 PBKDF2 或更好的是,随机选择一个密钥)从密码中派生密钥,则可以将其(以十六进制编码)提供给 enc带有-K 选项的命令,以及使用-iv 选项的IV。我没有检查您是否还需要 -nosalt 选项以避免在这种情况下抱怨幻数。

    【讨论】:

      【解决方案2】:

      查看crypto.createCipher() 函数的文档,它提到OpenSSL EVP_BytesToKey() 函数用于从密码中获取密钥,就像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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-07
        • 2010-11-03
        • 1970-01-01
        • 1970-01-01
        • 2015-10-06
        • 2018-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多