AES : JAVA coding
Hello..it’s been a long time since my last post. Actually i am a bit busy with my project going to ITEX exhibition this friday.
Now i am going to share with you all an example of AES encryption. This AES encryption used password from user as a key. Firstly, let me tell you more about AES.
Strictly speaking, AES is not precisely Rijndael (although in practice they are used interchangeably) as Rijndael supports a larger range of block and key sizes; AES has a fixed block size of 128 bits and a key size of 128, 192, or 256 bits, whereas Rijndael can be specified with key and block sizes in any multiple of 32 bits, with a minimum of 128 bits and a maximum of 256 bits.
Due to the fixed block size of 128 bits, AES operates on a 4×4 array of bytes, termed the state (versions of Rijndael with a larger block size have additional columns in the state). Most AES calculations are done in a special finite field. [source: wikipedia]
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
byte[] salt = {
(byte)0xc7, (byte)0×73, (byte)0×21, (byte)0×8c,
(byte)0×7e, (byte)0xc8, (byte)0xee, (byte)0×99,
(byte)0xc7, (byte)0×73, (byte)0×21, (byte)0×8c,
(byte)0×7e, (byte)0xc8, (byte)0xee, (byte)0×99
};int count = 16;
IvParameterSpec iv = new IvParameterSpec(salt);
generator.init(pBytes, salt, count);
ParametersWithIV params = (ParametersWithIV)
generator.generateDerivedParameters(128, 128);KeyParameter keyParam = (KeyParameter) params.getParameters();
SecretKeySpec key = new SecretKeySpec(keyParam.getKey(), “AES”);
String password = “secretkey”;
String PT = “Attack at dawn”;byte[] pBytes = password.getBytes();
Cipher cipher = Cipher.getInstance(”AES/CBC/PKCS5Padding”,”BC”);
cipher.init(Cipher.ENCRYPT_MODE,key,iv);byte[] cipherText = cipher.doFinal(PT.getBytes(”ASCII”));
Base64 b64 = new Base64();String b64ctxt = new String(Base64.encode(cipherText), “ASCII”);
String b64key = new String(Base64.encode(key.getEncoded()), “ASCII”);System.out.println(”Ciphertext = ” + b64ctxt);
System.out.println(”B64 key = ” + b64key);byte[] newCtxt = Base64.decode(b64ctxt);
cipher.init(Cipher.DECRYPT_MODE, key,iv);
byte[] plainBytes = cipher.doFinal(newCtxt);
String newPlainText = new String(plainBytes, “ASCII”);
System.out.println(”Plaintext = [” + newPlainText + “]”);
Thats all folks..Hope this would help. Just drop a comment if something is not right about the coding.
Thank you for reading this post. You can now Leave A Comment (0) or Leave A Trackback.
Post Info
This entry was posted on Tuesday, May 6th, 2008 and is filed under ComputerScience, JAVA.You can follow any responses to this entry through the Comments Feed. You can Leave A Comment, or A Trackback.
Previous Post: Best joke in Britain »
Next Post: Islam »











