Guys I am working on WP8 C# project and I'm having a problem with AES encryption in C#.
I have written code that encrypts a byte array with a key and an IV and returns a byte array;
AES Encryption in C#
public byte[] encryptAESWithIV(byte[] key, byte[] Text)
{
byte[] encrypted = new byte[48];
byte[] iv = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
encrypted = EncryptStringToBytes_Aes(toHex(Text), key, iv);
byte[] output = new byte[encrypted.Length + iv.Length];
Array.Copy(iv, 0, output, 0, iv.Length);
Array.Copy(encrypted, 0, output, iv.Length, encrypted.Length);
return output;
}
AES Encryption in Java (Android code)
public static byte[] encryptAESWithIV(byte[] key, byte[] clearText)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidParameterSpecException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
SecretKeySpec skeySpec = new SecretKeySpec(key, CIPHER_AES);
Cipher cipher = Cipher.getInstance(CIPHER_AES_MODE);
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
//random.nextBytes(iv);
try {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv));
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
byte[] encrypted = cipher.doFinal(clearText);
byte[] output = new byte[encrypted.length + iv.length];
System.arraycopy(iv, 0, output, 0, iv.length);
System.arraycopy(encrypted, 0, output, iv.length, encrypted.length);
Log.v("encrypt-length",""+encrypted.length);
Log.v("iv-length",""+iv.length);
//Log.d("output_bytes", Arrays.toString(output));
return output;
}
In both cases I have given the same IV, Text and key.
In C# I did not get the same result as with the Java code. The Java code is correct and I want to get the same result in C#.