Showing posts with label Rijndael. Show all posts
Showing posts with label Rijndael. Show all posts

Thursday, 8 January 2009

AES in Java and C#

In a recent project I had to implement some symmetric encryption algorithm (AES) in both Java and C# and make sure that the Java implementation could encrypt/decrypt the data decrypted/encrypted with the C# version..
So..

In Java:


Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(passwordKey, "AES");

Note passwordKey must be of 16 bytes in length for 128 bits encryption.

IvParameterSpec ivParameterSpec = new IvParameterSpec(rawSecretKey);

Then I decided to use Base 64 encoding for sharing data between C# and Java.
The cipher method is:

public String encryptAsBase64(byte[] clearData) throws Exception {
BASE64Encoder _64e = new BASE64Encoder();
byte[] encryptedData = encrypt(clearData);
return _64e.encode(encryptedData);
}

public byte[] encrypt(byte[] clearData) throws Exception {
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] encryptedData = aesCipher.doFinal(clearData);
return encryptedData;
}


Now, let's see how do decrypt in C#:


const string password = ...;
RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform rijndaelDecryptor =
rijndael.CreateDecryptor(passwordKey, passwordKey);

Then

byte[] newClearData =
rijndaelDecryptor.TransformFinalBlock(cryptedData, 0, cryptedData.Length);


You can use the class Convert for Base 64 encoding.

Blog Archive