Sunday, April 27, 2014

Asymmetric Encryption in Java

Asymmetric encryption uses a pair of public and private key to encrypt and decrypt messages. A message that is encrypted using a public or private key can only be decrypted using the other corresponding private or public key. RSA is an algorithm that is widely used to generate public and private key pair. RSA allows us to define how long the key is, 1024, 2048, or 4096 bits. Let's now try how to implement asymmetric encryption in Java.


First, we define the message that we want to encrypt and convert it to array of byte.


Then, we created a KeyPairGenerator object that will generate a pair of public-private key for us. We passed RSA, the algorithm name that will be used to generate the keys and then initialized it with the key size of 2048 bits. We can also initialize it with key size of 1024 or 4096 bits depending on our need. One thing to note is the longer the key, the longer it takes to generate the public-private key.


In the code above, we obtain the public and private key objects. Usually, the keys are then serialized to a file so that it can be read later to encrypt or decrypt messages.


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 RSA, we use RSA/ECB/PKCS1Padding. We can use other transformation string of our preference.

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


After everything is ready, we called doFinal() on Cipher object to start the encryption. The result is shown below:


After successfully encrypting the message now we will try to decrypt it. The code below shows how we do this by simply passing the private 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:

0 comments:

 

©2009 Stay the Same | by TNB