Sunday, February 12, 2012

Encryption with AES

Java Cryptography Architecture (JCA) provides support for encryption/decryption for most of the popular algorithms (AES, TripleDES, RSA, PBE, ..)

Here we will see how to do a symmetric encryption (same key for encrypt/decrypt) using AES.

The basic idea in JCA is to create a "cipher" using the secret key. Then use the cipher to encrypt/decrypt.

In your /src/org/confucius, create a class AESEncryption.java, like this:

 package org.confucius;  

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;

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

public class AESEncryption {

public static void main(String[] args) {
String keyString = "TOP-SECRET-KEY-SHARE-ONLY-WITH-INTENDED-RECEPIENT";
String secretMessageString = "For your eyes only...";

try {
// Create a AES Key
MessageDigest digester = MessageDigest.getInstance("SHA-256");
digester.update(keyString.getBytes());
byte[] key = digester.digest();
KeySpec keySpec = new SecretKeySpec(key, "AES" );

// Encrypt
Cipher encryptCipher = Cipher.getInstance("AES");
encryptCipher.init(Cipher.ENCRYPT_MODE, (Key) keySpec);
byte[] secretMessage = secretMessageString.getBytes();
byte[] encryptedMessage = encryptCipher.doFinal(secretMessage);
System.out.println("Encrypted Message = " + new String(encryptedMessage));

// Decrypt
Cipher decryptCipher = Cipher.getInstance("AES");
decryptCipher.init(Cipher.DECRYPT_MODE, (Key) keySpec);
byte[] decryptedMessage = decryptCipher.doFinal(encryptedMessage);
System.out.println("Decrypted message = " + new String(decryptedMessage));

} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

}



In this example code, we do both the encryption and decryption.

We create a KeySpec using the key string, then a cipher which uses the KeySpec, then use the cipher to encrypt/decrypt.

R-click on this file in your Eclipse navigator view, and select Run As->Java Application.

In the console, you will see both the encrypted and decrypted strings.

No comments: