Tuesday, March 3, 2009

Code : BlockDecryptor class


I need to encrypt the string using AES encryption and CBC mode.

The way given in one of the post 'How to - Use Basic Encryption'. This code works fine.

But when I am encrypting the string using blockdescryptor and CBCBlockDescryptor the string is not encrypted fully.

Now the question was “How can I encrypt the string properly?”.

Following is the code:

private static byte[] encrypt(byte[] keyData, byte[] data) 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 key = new AESKey(keyData, 0, 128);

// Now, we want to encrypt the data.
// First, create the encryptor engine that we use for the actual
// encrypting of the data.
AESEncryptorEngine engine = new AESEncryptorEngine(key);

String strInitVector = "1234567890123456";
byte[] initVector = strInitVector.getBytes();
// Create a new initialization vector using the 8 bytes in initVector
InitializationVector iv = new InitializationVector(initVector);
// Create a BlockEncryptor to hide the engine details away.
ByteArrayOutputStream output = new ByteArrayOutputStream();
BlockEncryptor encryptor = new BlockEncryptor(new CBCEncryptorEngine(engine, iv) , output);
//BlockEncryptor encryptor = new BlockEncryptor(fengine , output);
encryptor.write(data, 0, data.length);
int nSize = output.size();
encryptor.flush();
output.close();
//encryptor.close(); // At this line application is throwing uncaught exception

// Now, the encrypted data is sitting in the ByteArrayOutputStream.
// We simply want to retrieve it.
return output.toByteArray();
}

The string given for encryption is "The quick brown fox jumped over the lazy dog".

Actual encrypted string from PHP for this string is of 42 characters. Where as my application is giving me the encrypted string of 32 characters. After decryption I am getting the plain text as "The quick brown fox jumped over ".

I have tried the same thing,appended '0' byte at the end of the string if the string length is less than block length.

And, It is working perfect.

No comments:

Post a Comment

Place your comments here...