Thursday, 15 August 2013

Symmetric Key Encryption / Decryption

In this chapter we will see how we can do encryption / decryption using symmetric key method. For more details about Java security read Java Security
In this example we will use KeyGenerator class and generate the symmetric key and than encrypt and decrypt a String text using Cipher class.

For a maven project you will need the apache-common-codec jar as a dependency or else just download the jar and paste it in the folder which is in the classpath.

Maven dependency:
<dependency>
 <groupId>commons-codec</groupId>
 <artifactId>commons-codec</artifactId>
 <version>1.8</version>
</dependency>

Main Class
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class SymmetricKey {

 public static void main(String[] args) throws Exception {

  //Generate Symmetric key
  KeyGenerator generator = KeyGenerator.getInstance("AES");
  generator.init(128);
  SecretKey key = generator.generateKey();
  byte[] symmetricKey =key.getEncoded();
  
  System.out.println("key : "+symmetricKey);
  
  //Encrypt Data
  String encryptedData = encryptWithAESKey("asd", symmetricKey);
  
  System.out.println("Encrypted Data : " + encryptedData);
  
  //Decrypt Data
  System.out.println("Decrypted Data : " +decryptWithAESKey(encryptedData, symmetricKey));

 }



 public static String encryptWithAESKey(String data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException,
   InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  SecretKey secKey = new SecretKeySpec(key,"AES");

  Cipher cipher = Cipher.getInstance("AES");
  
  cipher.init(Cipher.ENCRYPT_MODE, secKey);
  byte[] newData = cipher.doFinal(data.getBytes());
  
  return Base64.encodeBase64String(newData);
 }

 public static String decryptWithAESKey(String inputData, byte[] key) throws NoSuchAlgorithmException,
   NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  Cipher cipher = Cipher.getInstance("AES");
  SecretKey secKey = new SecretKeySpec(key, "AES");

  cipher.init(Cipher.DECRYPT_MODE, secKey);
  byte[] newData = cipher.doFinal(Base64.decodeBase64(inputData.getBytes()));
  return new String(newData);

 }
}

In the above example KeyGenerator is instantiated with AES algorithm. Every Java Implementation needs to implement one of below given algorithm.
AES (128)
DES (56)
DESede (168)
HmacSHA1
HmacSHA256
AES is Advanced Encryption System algorithm. The data will be encrypted using this Algorithm. The statement generator.init(128) provides the size of the key in bits. This can be 128,192,256 according to the AES specification.
After the key is generated we have created a instance of Cipher class and instantiated it with AES. And than we set it to ENCRYPT MODE and call doFinal which encrypts the data. For decryption again we create a instance of Cipher with DECRYPT MODE and decrypt the data using the same key used for encryption.
You might have noticed that we are encoding the encrypted data with Base64. This is required if you want to save the encrypted data in a file and send it across. It guarantees that the data will not get lost. 
Java Examples

No comments:

Post a Comment

Share the post