Sunday, April 27, 2014

Symmetric Encryption in Java

Symmetric encryption uses a secret key (also known as private key) to encrypt and decrypt messages. Data Encryption Standard (DES) is an algorithm that is widely used to generate secret key. Other algorithms are AES and DEDede.

Session key is a term that is used to represent a secret key that its lifetime is limited. For example a secret key that is generated to encrypt a digital conversation. The key is destroyed after the conversation is finished. DES allows us to use 8 characters string as a key while AES allows 16 characters key and DESede allows 24 characters key. Let's try to encrypt and decrypt string in Java.


First we define our secret key string. Since we want to try AES, we have a 16 characters string as the secret key. We also created the message and convert it to an array of byte.


Next we created a SecretKey object by passing our secret key and the algorithm name of our preference. In this case we passed AES and its 16 bytes secret key.


Next we created a Cipher object by passing, what Javadoc refers as, a transformation. It is a string that describes the operations to be performed on the given input to produce some output. There are several transformation strings we can choose depending on the algorithm we use. Since in this case we use AES, we use AES/ECB/PKCS5Padding. We can use other transformation string of our preference.

Then we initialize the Cipher object by passing it the secret key object we created before and a flag to tell the Cipher that we want to do encryption as stated on ENCRYPT_MODE.


Now we can start encryption by calling doFinal() on the Cipher object as we did above. The encrypted text is show below:

After successfully encrypting the message now we will try to decrypt it. The code below shows how we do it by simply passing the secret key and a flag indicating that now we are interested in decrypting a text instead of encrypting it.


The decryption happens when we call doFinal() on Cipher object as we did when encrypting message.


The decryption result is shown below:

Instead of providing a string of secret key, Java provides us a secret key generator class named KeyGenerator. Our code below shows how we can take advantage of this class to generate a random secret key:

KeyGenerator takes algorithm name as a parameter to generate the secret key for us.

0 comments:

 

©2009 Stay the Same | by TNB