Tuesday, May 4, 2010

AES Encryption

AES is a standard private-key or symmetric cryptography. It supports combination of key and block sizes of 128, 192, and 256.

In Blackberry AES encryption can be achieved as follows:

import java.io.*;
import net.rim.device.api.io.*;
import net.rim.device.api.crypto.*;

import net.rim.device.api.util.*;

/**
* This is utility class for doing AES encryption and decryption.
* It uses 'PKCS5' as padding.
*
*/
public class AESUtil
{
/**
* Encrypts data using specified key data using AES algorithm.
*
* @param arrKeyData Key data that will be used for encryption.
* @param arrData Data to be encrypted.
*
* @return Encryped data in byte array.
*/
public static byte[] fnEncrypt(byte[] arrKeyData, byte[] arrData)
throws CryptoException, IOException
{
// Create the AES key to use for encrypting the data.
// This will create an AES key using as much of the keyData as possible.
AESKey oKey = new AESKey(arrKeyData);

AESEncryptorEngine oEngine = new AESEncryptorEngine(oKey);

PKCS5FormatterEngine oPKCS5Engine = new PKCS5FormatterEngine(oEngine);

ByteArrayOutputStream oOutput = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor(oPKCS5Engine, oOutput);

encryptor.write(arrData);
encryptor.close();
oOutput.close();


return oOutput.toByteArray();
}

/**
* Decrypts encrypted data using specified key data using AES algorithm.
*
* @param arrKeyData Key data that will be used for decryption.
* @param arrEncryptedData Encryped data that is to be decrypted.
*
* @return Decrypted data in byte array.
*/
public static byte[] fnDecrypt(byte[] arrKeyData, byte[] arrEncryptedData)
throws CryptoException, IOException
{
// Create the AES key to use for encrypting the data.
// This will create an AES key using as much of the keyData as possible.
AESKey oKey = new AESKey(arrKeyData);

AESDecryptorEngine oEngine = new AESDecryptorEngine(oKey);

PKCS5UnformatterEngine oUEngine = new PKCS5UnformatterEngine(oEngine);

ByteArrayInputStream oInput = new ByteArrayInputStream(arrEncryptedData);
BlockDecryptor oDecryptor = new BlockDecryptor(oUEngine, oInput);


byte[] arrTemp = new byte[100];
DataBuffer oBuffer = new DataBuffer();

int nBytesRead = -1;

while(-1 < (nBytesRead = oDecryptor.read(arrTemp)))
{
oBuffer.write(arrTemp, 0, nBytesRead );
}

return oBuffer.getArray();
}
}

1 comment:

Anonymous said...

Thank you for sharing this program. I used the code in my application and it worked so well. Can you please share some more security algorithms ?
digital id