I have an old embedded device that expects an encrypted password with a given cipher, key and IV. An existing application written in .NET framework creates an AES-128-CBC encrypted string, and I'm re-writing this in Node.js using the Crypto library.
However, when I encrypt a string with the same key and IV in Node.js, the output is not the same as in .NET. I've double checked the encryption with online tools, and they yield the same result as .NET, so Node.js Crypto is the odd one out.
The C# code for .NET (the key and IV has been substituted for demonstration purpose):
byte[] encrypted;
using (AesManaged aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.Key = new byte[] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
aes.IV = new byte[] { 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99 };
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write("admin");
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
This gives the Base64 string gE1twb8LV/44oO/6UKwwCg==.
I've tested the same cipher, key and IV with online tools, and they give the same output.
My Node.js code:
const crypto = require('crypto');
const key = Buffer.from('00112233445566778899aabbccddeeff', 'hex');
const iv = Buffer.from('aabbccddeeff00112233445566778899', 'hex');
const plaintext = 'admin';
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
cipher.update(Buffer.from('admin'));
var encrypted = cipher.final().toString('base64');
This gives the Base64 string 4TT9E4WDH/TmlKjJdVFeHQ==.
I have tried everything I can think of with no luck. I've noticed that the .NET code specifies a zero-padding, but I've not been able to find a way to set this in the Node.js Crypto. I'm guessing this is probably why it doesn't give the same output.
Anyone know how to specify zero-padding in Node.js Crypto?