0

I am trying to decrypt Aes that was created from the JavaScript AES Encryptor from the CryptoJS library. I am trying to read a string that was encrypted by that library and decrypt it within my C# project using the following:

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;
}

The data was encrypted in JavaScript as follows:

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

When I attempt to use my method to decrypt the data I get the following error message:

CryptographicException: Invalid input block size.

Which is triggered by cs.Close();. It could be that secret hasn't been implemented, which I am not exactly sure where that would go in this...

How can I implement this decryptor to work alongside the JavaScript Library?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • It appears from [this](https://stackoverflow.com/a/27231514/4684493) that crypto-js is using a lot of defaults regarding keysize, padding, mode and iv. You need to specify all of those defaults in your decryption routine. I think you should not rely on those defaults, but rather specify them explicitly. – Hintham Oct 30 '18 at 16:43
  • I have tried implementing some of the data from that answer, Im still not getting it to work. I have updated the question to reflect the changes. – Get Off My Lawn Oct 30 '18 at 19:26
  • I'm not so sure about the iv and key. Those should be identical to what is used during encryption, but it looks like you are generating them. From my previously linked answer it looks like the key is generated from the passphrase, but it doesn't say how. BTW: the iv is not secret at all, it is often appended to the cipher when it is transmitted. I'm not familiar with the crypto-js library, but i find it's AES implementation a bit unusual. – Hintham Oct 30 '18 at 20:34

0 Answers0