Thursday, January 9, 2014

Encrypt and Decrypt AES CBC in Java


Here is an example about how to encrypt and decrypt an string using AES  CBC:

We will need:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;


    public static void main(String[] args) throws Exception {
     
        String IV = "51515151515151515151515151515151";
        String aeskey = "78A63D60DBDFC633BD9F8ACDAC27EBBA";
        String plaintext = "It doesnt work\0\0";
        String encrypted_data = "E491C75BF68E073F34DBB7B6392B1DB2";

     
        byte[] cipher = encrypt(plaintext, aeskey, IV);
        System.out.println(DatatypeConverter.printHexBinary(cipher));
        System.out.println("---");
     
 
        byte[] encrypted_data_bytes =
                      DatatypeConverter.parseHexBinary(encrypted_data);
 
        byte[] decrypted = decrypt(encrypted_data_bytes, aeskey, IV);
        System.out.println(DatatypeConverter.printHexBinary(decrypted));
        System.out.println( new String(decrypted,"UTF-8"));
     
   
    }  
 

  public static byte[] encrypt(String plainText, String encryptionKey, String IV)  {
      byte[] i = DatatypeConverter.parseHexBinary(IV);
      byte[] a = DatatypeConverter.parseHexBinary(encryptionKey);

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(a, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(i));
 
    return cipher.doFinal(plainText.getBytes("UTF-8"));
  }
   
 
    public static byte[] decrypt(byte[] cipherText, String encryptionKey, String IV) {
        byte[] i = DatatypeConverter.parseHexBinary(IV);
        byte[] a = DatatypeConverter.parseHexBinary(encryptionKey);
     
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key = new SecretKeySpec(a, "AES");
        cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(i));
     
        return cipher.doFinal(cipherText);
    }

If we run the example the output will be:

run:
E491C75BF68E073F34DBB7B6392B1DB2
---
497420646F65736E7420776F726B0000
It doesnt work

Which means that the code really works :)

Hope help!


No comments:

Post a Comment