Search code examples
javascriptc#aesbouncycastlecryptojs

Different AES implementations don't agree


I have to encrypt a piece of data using both C#, and Javascript. I'm using Bouncy Castle in C# and Crypto-JS in Javascript.

The problem I am facing is that even though all the parameters are equal (OFB with no padding, and the IV is always 0), I don't get the same output with both libraries. The consequence of that is also that I can't decrypt with one what was encrypted with the other.

Here is my C# code for encrypting:

byte[] iv = new byte[16];

BufferedBlockCipher aes = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), 16));
ParametersWithIV ivAndKey = new ParametersWithIV(new KeyParameter(stretchedKey), iv);
aes.Init(true, ivAndKey);

int minSize = aes.GetOutputSize(privateKey.Length);
byte[] outBuf = new byte[minSize];
int length1 = aes.ProcessBytes(privateKey, 0, privateKey.Length, outBuf, 0);
int length2 = aes.DoFinal(outBuf, length1);

byte[] encryptedKey = iv.Concat(outBuf.Take(length1 + length2)).ToArray();

My Javascript code is the following for encrypting (try it on JSFiddle here: http://jsfiddle.net/gCHAG/424/):

var key = Crypto.util.hexToBytes('59b50e345cab8b6d421b161918ea3fbd7e5921eea7d43d1ac54fa92cca452bb5');
var iv  = Crypto.util.hexToBytes('00000000000000000000000000000000');
var message = Crypto.util.hexToBytes('3b16601d0a7e283c1f24d30ec214676885096cb0bbf3998012a2be87c5a58d89');

var encrypted = Crypto.AES.encrypt(message, key, { iv: iv, asBytes: true, mode: new Crypto.mode.OFB(Crypto.pad.NoPadding) });

I get the following from the bouncy castle implementation: 578934dbb576dc986a531f09e8d5abd5b01dc1bfd3ededd222ff8aa6e4bfdbf2

And the following from Crypto-JS: 578946591ce2d787cbe41bec77a58dac66e6007fb722b1af847ecc3bf4212cea

Note how the first two bytes are the same, but then everything else is different.

To top it all up, when trying on an online tool, I get a third output (see http://aes.online-domain-tools.com/link/bd243g1VXbD7LUAS/): 57804D64A8...

I went through everything several times, but I don't see why I get different outputs.


Solution

  • CryptoJS seems to use an output of 128 bits per block for the key stream. You specify 16 bits per block for Bouncy. As 8 or 128 bits per block are common for OFB, and since 128 is the recommended output size, I guess you are just confusing bits and bytes in the Bouncy code.

    If you specify new OfbBlockCipher(new AesEngine(), 128) you should be OK.