I have legacy encryption code in C# and now I have to do same encryption in JavaScript. I've done some research and tried 3 different libraries, however couldn't get same results. Last library I used is CryptoJS and I must figure out why I'm getting different results.
Here are both code snippets:
C# code:
text = "chocolate";
PasswordHash = "hashhash";
SaltKey = "saltsaltsaltsa";
VIKey = "iviviviviviviviv";
byte[] plainTextBytes = Encoding.UTF8.GetBytes(text);
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
byte[] cipherTextBytes;
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memoryStream.ToArray();
cryptoStream.Close();
}
memoryStream.Close();
}
var result = Convert.ToBase64String(cipherTextBytes);
result ==> "8AbNsyyqHHfi/PEF/bbiew=="
JavaScript code:
pass = 'chocolate';
//Creating the Vector Key
var iv = CryptoJS.enc.Utf8.parse('iviviviviviviviv');
//Encoding the Password in from UTF8 to byte array
var passHash = CryptoJS.enc.Utf8.parse('hashhash');
//Encoding the Salt in from UTF8 to byte array
var Salt = CryptoJS.enc.Utf8.parse("saltsaltsaltsa");
//Creating the key in PBKDF2 format to be used during the encryption
var key128Bits1000Iterations = CryptoJS.PBKDF2(passHash, Salt, { keySize: 256 / 8, iterations: 1000 });
//Encrypting the string contained in cipherParams using the PBKDF2 key
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(pass), key128Bits1000Iterations, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.ZeroPadding });
var result = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
result = "dpgTA41PDyrM8ef9C1c8iA==“
Finally got a solution. Thanks to Luke Park who advised me that CryptoJS is using 4-byte (word) structure.
The issue which led to different results is that the key-size is (apparently) different. In C# 256/8 is actually 32 bytes length, however in CryptoJS, since using 4-bytes, 256/8 translates practically to 128 bytes length :(
Once I change the key size in the JS snippet to 256/32 ((256/32)*4 = 32) it worked perfectly and echo same results as the C# encryption method.
Thank you all Nir