Pages

Monday, 19 December 2016

How to ENCRYPT and DECRYPT using 256 bit key AES algorithm in java

Hi friends,here i am once again with one more interesting topic ,

public class AESAlgorithm {  
   
    private byte[] ivBytes;
 
    public String encrypt(String plainText,String sessionKey) throws Exception {
        SecretKeySpec secret = new SecretKeySpec(sessionKey.getBytes(), "AES");
        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(plainText.getBytes("UTF-8"));
        return new String(Base64.encode(encryptedTextBytes));
    }

    public String decrypt(String encryptedText,String sessionKey) throws Exception
    {

        byte[] encryptedTextBytes = Base64.decode(encryptedText.getBytes());
        SecretKeySpec secret = new SecretKeySpec(sessionKey.getBytes(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
   
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new String(decryptedTextBytes);
    }
public String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[32];
        random.nextBytes(bytes);
        String s = new String(bytes);
        return s;
    }
    public static void main(String[] args) throws Exception
{
AESAlgorithm c=new AESAlgorithm();
String sessionKey=c.generateSalt();
String str="Ashish Shukla";
Strinf encryptedText=c.encrypt(str,sessionKey);
System.out.println("ENCRYPTED text ="+encryptedText);
System.out.println("ENCRYPTED text= "+c.decrypt(encryptedText,sessionKey));
}
}


Till then keep asking-:)
And provide your feedback in comment box.

No comments:

Post a Comment