在Node.js中解密文件会引发错误,但可以在C#中使用Bouncy Castle进行解密

时间:2018-09-22 20:23:49

标签: javascript c# node.js encryption bouncycastle

我遇到一个问题,我得到了一个要解密的文件以及密钥,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

0 个答案:

没有答案