Wednesday, July 17, 2013

How To Encrypt and Decrypt With AES Algorithm in JAVA

AES (Advanced Encryption Standard) is one of the most commonly used encryption algorithm among Symmetric Encryption algorithms. As you know Symmetric Encryption algorithms use the same key for encryption and decryption. In other words, the key you used to encrypt the data should be used to decrypt the data again. (As you may already know in Asymmetric Encryption algorithms, a combination of private and public key are used.)

In AES the length of the key should be 128-bit(16 bytes), 192-bit(24 bytes) or 256-bit(32 bytes).

Following code shows you how to encrypt with AES.
  private static byte[] encrypt(String message) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    return c.doFinal(message.getBytes());
  }


Following code decrypts the encrypted bytes back in to the original String.
  private static String decrypt(byte[] encryptedText) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decValue = c.doFinal(encryptedText);
    String decryptedValue = new String(decValue);
    return decryptedValue;
  }

As you may have already noticed in above samples I have used a 128-bit key("ThisIs128bitSize"). Did you try a 192-bit or 256-bit key such as "LengthOfThisTextIs192bit". Sometimes you may get this kind of a error.

java.security.InvalidKeyException: Illegal key size or default parameters

If you get this error it means that your security policies do not allow you to use keys with more than 128-bit length. You can check this length by using 'getMaxAllowedKeyLength()' method as below.
int length = Cipher.getMaxAllowedKeyLength("AES");
System.out.println(length);//prints the max key length

Do following steps to override these settings.

☛ Download Java Cryptography Extension (JCE) Unlimited Strength zip file from following links and unzip     it.
    For Java 7 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

    For Java 6 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

☛ Copy all the .jar files from unzipped folder to /jre/lib/security folder. In any case you later need to
    switch to the original version, please keep a backup of original files before overwriting.

☛ Now run your code with 192-bit or 256-bit key. It will work.

If you get following error it means you have copied incorrect version of policy files. In other words your java version and policy file version are not matched. So make sure to add relevant version of policy files. Then it will work.

java.lang.SecurityException: Jurisdiction policy files are not signed by trusted signers!

1 comment: