如何使用CryptoJS加密的字符串实现AES解密?

时间:2018-10-30 16:33:45

标签: c# aes

我正在尝试从CryptoJS library解密从JavaScript AES加密器创建的Aes。我正在尝试读取由该库加密的字符串,并使用以下命令在我的C#项目中对其解密:

public static string Decrypt(string message, string secret, string salt = "zAvR2NI87bBx746n") {
  return Encoding.UTF8.GetString(AESDecryptBytes(
    Encoding.UTF8.GetBytes(message),
    Encoding.UTF8.GetBytes(secret),
    Encoding.UTF8.GetBytes(salt)
  ));
}

private static byte[] AESDecryptBytes(byte[] cryptBytes, byte[] passBytes, byte[] saltBytes) {
  byte[] clearBytes = null;

  // create a key from the password and salt, use 32K iterations
  // var key = new Rfc2898DeriveBytes(passBytes, saltBytes, 32768);
  var key = new Rfc2898DeriveBytes(passBytes, saltBytes, 1000);

  using (Aes aes = new AesManaged()) {
    // set the key size to 256
    aes.KeySize = 256;
    aes.Padding = PaddingMode.PKCS7;
    aes.Mode = CipherMode.CBC;
    aes.Key = key.GetBytes(aes.KeySize / 8);
    aes.IV = key.GetBytes(aes.BlockSize / 8);

    using (MemoryStream ms = new MemoryStream()) {
      using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)) {
        cs.Write(cryptBytes, 0, cryptBytes.Length);
        cs.Close();
      }
      clearBytes = ms.ToArray();
    }
  }
  return clearBytes;
}

按以下方式使用JavaScript加密数据:

// data is a JSON string
// gs.cryptoSecret is a string of random characters
let saveData = CryptoJS.AES.encrypt(data || '', gs.cryptoSecret).toString()

当我尝试使用我的方法解密数据时,出现以下错误消息:

  

CryptographicException:无效的输入块大小。

哪个由cs.Close();触发。可能是secret尚未实现,我不确定这会在哪里...

如何实现该解密器与JavaScript库一起使用?

0 个答案:

没有答案