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?