【问题标题】:Encrypt in Node.JS Crypto (aes-256-cbc) then decrypt in OpenSSL CLI在 Node.JS Crypto (aes-256-cbc) 中加密,然后在 OpenSSL CLI 中解密
【发布时间】: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


【解决方案1】:

我相信bad decrypt的意思是openssl不理解加密密钥

这就是发生的事情。

  1. 作为第一步crypto 使用提供的密码和盐生成加密密钥: crypto.scrypt(password, 'salt', 32,...
  2. 作为第二步,它会生成一个初始化向量 (iv): crypto.randomFill(new Uint8Array(16)
  3. 最后它使用生成的密钥和 iv 创建密码并实际加密文件: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}`);
  });
});

【讨论】:

    猜你喜欢
    • 2015-04-15
    • 2013-08-11
    • 2023-02-23
    • 2014-02-06
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多