AES 256bit Encryption/Decryption and storing in the database using java

AES 256bit Encryption/Decryption and storing in the database using java

AES stands for Advanced Encryption Standards. AES is based on the Rijndael ciper developed by two Belgian cryptographers, Joan Daeman and Vincent Rijmen. AES was designed to be efficient in both hardware and software and supports a block length of 128bits and key lengths of 128,192 and 256 bits. In security point of view AES is more secure when compared to DES Encryption methods.

Here you will learn how to encrypt and decrypt in java using above mentioned AES 256bit Encryption method and How to store it in a database.

I searched about this on internet but I couldn’t find a full tutorial on this. Even though there are tutorials on encryption and decryption, they do not say about storing it in database. Here you can learn about encryption decryption plus store in database.

Here the encrypted word is concatenated with the things that are needed for decryption. There fore the Encrypted word can be stored in database and decrypted.

You should have NetBeans or Eclipse IDE

Create new Project

First you download commons-codec-1.10 under binaries from here.

Extract it and add commons-codec-1.10 jar library to your project.

you have to create following three classes.

  1. Encryption.java
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Encryption {
  public String encrypt(String word) throws Exception {
    byte[] ivBytes;
String password="Hello";
/*you can give whatever you want for password. This is for testing purpose*/
    SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
byte[] saltBytes = bytes;
    // Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(),saltBytes,65556,256);
     SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
     //encrypting the word
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
     byte[] encryptedTextBytes =                          cipher.doFinal(word.getBytes("UTF-8"));
     //prepend salt and vi
      byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
      System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
       System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
       return new Base64().encodeToString(buffer);
    }
}

2. Decription.java

import java.nio.ByteBuffer;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Decryption {
  @SuppressWarnings("static-access")
public String decrypt(String encryptedText) throws Exception {
    String password="Hello";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    //strip off the salt and iv
ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
    byte[] saltBytes = new byte[20];
buffer.get(saltBytes, 0, saltBytes.length);
byte[] ivBytes1 = new byte[cipher.getBlockSize()];
buffer.get(ivBytes1, 0, ivBytes1.length);
byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];

buffer.get(encryptedTextBytes);
    // Deriving the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);
    SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
    byte[] decryptedTextBytes = null;
    try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}

return new String(decryptedTextBytes);
  }
}

3. Test.java

public class Test{
/**
* @param args the command line arguments
*/
  public static void main(String[] args) throws Exception{
Encryption en=new Encryption();
String encryptedWord=en.encrypt("Test");
System.out.println("Encrypted word is : " + encryptedWord);
Decryption de =new Decryption();
System.out.println("Decrypted word is : " + de.decrypt(encryptedWord));
  }
}

Store in the Database

when you are going to store the encrypted password in the database, You just store encrypted word in above Test.java in the databases as string. You can decrypt it using the Decryption.java class as mentioned in Test.java. Here What has done is all salt bytes, iv bytes and encrypted text bytes are concatenated and get as encrypted word. When it is decrypting again iv bytes and salt is stripped off.

Reference : Implement AES-256 encryption/decryption using Java

Hope this would be Helpful. Cheers!!!!! Enjoy Coding!!!!!!!!!!!