I have some C# code that uses AES 256 to encrypt data, using a custom key and iv. I'm trying to recreate the code using CryptoJS library. They give different outputs, and I can't figure out what I'm doing wrong.
The input for both is string '675675'.
C# code gives yzFi7xGovxl0qcLsMoXZ9Q== while JS code gives zJtuaFJcJdeSfZxneb6bTYDPjoH3QAz87HTaaLyn5Zc=
Here's the C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace Whatever.Class
{
public class Program
{
public static void Main(string[] args)
{
string moo = Encrypt_AES256.Encrypt256("675675", "5TGB&BJD!(JM(IK<5TGB&YHN7UJM(IK<", "!QAYDF7N#EDC4RFV");
Console.WriteLine(moo+"\n");
}
}
public class Encrypt_AES256
{
public static string Encrypt256(string text, string AesKey256, string AesIV256)
{
// AesCryptoServiceProvider
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = 128;
aes.KeySize = 256;
aes.IV = Encoding.UTF8.GetBytes(AesIV256);
aes.Key = Encoding.UTF8.GetBytes(AesKey256);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
byte[] src = Encoding.Unicode.GetBytes(text);
using (ICryptoTransform encrypt = aes.CreateEncryptor())
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
// Convert byte array to Base64 strings
return Convert.ToBase64String(dest);
}
}
}
}
Here's the JS code I attempted to write, using CryptoJS lib:
const encryptWithAES = message => {
const key = CryptoJS.lib.WordArray.create('5TGB&BJD!(JM(IK<5TGB&YHN7UJM(IK<');
const iv = CryptoJS.lib.WordArray.create('!QAYDF7N#EDC4RFV');
const wordArray = CryptoJS.lib.WordArray.create(message);
const cipher = CryptoJS.AES.encrypt(wordArray, key, {
iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
return cipher.toString();
}
console.log(encryptWithAES('675675'));
What am I doing wrong in the JS code?
Assumptions:
- I couldn't find any equivalent for mentioning BlockSize and KeySize like in C#. It looks like CryptoJS picks that up on its own when reading the key and iv input.
- Using base64 still didn't give me the right answer, so I didn't add it in the code sample.