首页 > 解决方案 > 在 Node.js 中解密文件会引发错误,但能够在 C# 中使用 Bouncy Castle 进行解密

问题描述

我遇到了一个问题,我得到了一个要解密的文件以及密钥、IV 和加密方法 ( aes-256-ctr)。我一直在努力使用 node.js 解密它,并一直遇到错误,说 IV 长度无效。我还获得了使用 C# 中的 BouncyCaste 库解密文件的方法。C# 方法似乎工作正常,IV 没有问题。为了避免这个错误,我需要在节点中做些什么与在 C# 中所做的不同?

工作 C# 解密(注意:IV 在文件名中)

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace c_app
{
  class Program
  {
    static void Main(string[] args)
    {
      var baseFolder = Directory.GetCurrentDirectory();

      // Create parameters
      var myDi = new DirectoryInfo(baseFolder);
      string keyString = "xxxxxxxxxxxxx32BitKeyxxxxxxxxxxx";
      byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(keyString);
      var c = CipherUtilities.GetCipher("AES/CTR/NoPadding");
      KeyParameter sk = ParameterUtilities.CreateKeyParameter("AES", keyBytes);

      // Get the IV
      var files = myDi.GetFiles("001398.20180823.000_1966151284357350418");
      var fileInfo = files[0];
      var pathSplit = fileInfo.FullName.Split('_');
      var filePath = pathSplit[0];
      var iv = long.Parse(pathSplit[1]);

      // Decrypt the file
      var base64String = File.ReadAllText(fileInfo.FullName);
      c.Init(false, new ParametersWithIV(sk, BitConverter.GetBytes(iv)));
      var inputBytesToDecrypt = Convert.FromBase64String(base64String);
      var decryptedBytes = c.DoFinal(inputBytesToDecrypt);
      var decryptedText = ASCIIEncoding.UTF8.GetString(decryptedBytes);

      // Write file back to current directory
      File.WriteAllBytes(string.Format(@"{0}/decrypted.csv", myDi.FullName), decryptedBytes);
    }
  }
}

我在 Node.js 中的尝试

var crypto = require('crypto');
var fs = require('fs');

var iv = Buffer.from('1966151284357350418', 'base64'); // Experimenting with encoding types like base64
var key = Buffer.from('xxxxxxxxxxxxx32BitKeyxxxxxxxxxxx');

fs.readFile('./001398.20180823.000_1966151284357350418', (err, encryptedText) => {
  if (err) throw err;

  var decipher = crypto.createDecipheriv('aes-256-ctr', key, iv); // <--- Error thrown here
  decrypted = decipher.update(encryptedText, 'binary', 'utf8');
  decrypted += decipher.final('utf8');
  console.log(decrypted);
});

如果有帮助,我还获得了使用 BouncyCastle 加密文件的方法,可以在此处找到:https ://pastebin.com/PWNzDum3

标签: javascriptc#node.jsencryptionbouncycastle

解决方案


推荐阅读