Hello everyone, I got a small question on encryption, actually I am trying to learn the various techniques to encrypt a message. Now I am trying AES, using the built in security package in Java. The problem is that I am having a problem with this encryption algorithm. Actually I've got a sample of the AES on the net and trying to understand the logic but I am stuck. Here's the code:
import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import java.io.*; public class AES { public static String asHex (byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } public static void main(String[] args) throws Exception { String message="AES still rocks!!"; // Get the KeyGenerator KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); // 192 and 256 bits may not be available // Generate the secret key specs. SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // Instantiate the cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes()); System.out.println("encrypted string: " + asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] original = cipher.doFinal(encrypted); String originalString = new String(original); System.out.println("Original string: " + originalString + " " + asHex(original)); } }Questions: What is the key in this program? How can I change the key?
Finally when I try the program, I've got the following results
encrypted string: 91369a3b74c6feede0eff48fcf004f67d26cdd0b4907b44fd2147a4077ded0d1 Original string: AES still rocks!! 414553207374696c6c20726f636b732121
When the message has been decrypted, what does this "414553207374696c6c20726f636b732121" means?
Thanks a lot in advance guys. I would really appreciate if you could help me on this. I just want to understand the logic behind it in order to use it later on. Until now, I have not find a more easier code than this one. If you have one which is easier, please let me now. Again, thanks
Regards, Mike
C:\Javaprg>java AES Hello
encrypted string: 3ac3299a9ff3bfbe4b6ff02ece2590dd
Original string: Hello 48656c6c6f
Following Method return Encoded String. Content of buff (byte array) represent some non-printable characters, so the author of this code has write asHex() method to generate a string which could be displayed or stored into a disk file or database.
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}