AES Encryption Logic

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Mar 2009
Posts: 123
Reputation: neutralfox is an unknown quantity at this point 
Solved Threads: 0
neutralfox neutralfox is offline Offline
Junior Poster

AES Encryption Logic

 
0
  #1
May 8th, 2009
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:

  1. import java.security.*;
  2. import javax.crypto.*;
  3. import javax.crypto.spec.*;
  4. import java.io.*;
  5.  
  6.  
  7. public class AES {
  8.  
  9.  
  10. public static String asHex (byte buf[]) {
  11.  
  12. StringBuffer strbuf = new StringBuffer(buf.length * 2);
  13. int i;
  14.  
  15. for (i = 0; i < buf.length; i++) {
  16. if (((int) buf[i] & 0xff) < 0x10)
  17. strbuf.append("0");
  18.  
  19. strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
  20. }
  21.  
  22. return strbuf.toString();
  23. }
  24.  
  25. public static void main(String[] args) throws Exception {
  26.  
  27. String message="AES still rocks!!";
  28.  
  29. // Get the KeyGenerator
  30. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  31. kgen.init(128); // 192 and 256 bits may not be available
  32.  
  33.  
  34. // Generate the secret key specs.
  35. SecretKey skey = kgen.generateKey();
  36. byte[] raw = skey.getEncoded();
  37.  
  38. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  39.  
  40.  
  41.  
  42. // Instantiate the cipher
  43. Cipher cipher = Cipher.getInstance("AES");
  44.  
  45.  
  46.  
  47. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  48. byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());
  49. System.out.println("encrypted string: " + asHex(encrypted));
  50.  
  51. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  52. byte[] original = cipher.doFinal(encrypted);
  53. String originalString = new String(original);
  54. System.out.println("Original string: " + originalString + " " + asHex(original));
  55. }
  56. }

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
Last edited by neutralfox; May 8th, 2009 at 6:48 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 2,638
Reputation: adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of adatapost has much to be proud of 
Solved Threads: 472
Moderator
adatapost's Avatar
adatapost adatapost is offline Offline
Posting Maven

Re: AES Encryption Logic

 
0
  #2
May 9th, 2009
Originally Posted by neutralfox View Post
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:

  1. import java.security.*;
  2. import javax.crypto.*;
  3. import javax.crypto.spec.*;
  4. import java.io.*;
  5.  
  6.  
  7. public class AES {
  8.  
  9.  
  10. public static String asHex (byte buf[]) {
  11.  
  12. StringBuffer strbuf = new StringBuffer(buf.length * 2);
  13. int i;
  14.  
  15. for (i = 0; i < buf.length; i++) {
  16. if (((int) buf[i] & 0xff) < 0x10)
  17. strbuf.append("0");
  18.  
  19. strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
  20. }
  21.  
  22. return strbuf.toString();
  23. }
  24.  
  25. public static void main(String[] args) throws Exception {
  26.  
  27. String message="AES still rocks!!";
  28.  
  29. // Get the KeyGenerator
  30. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  31. kgen.init(128); // 192 and 256 bits may not be available
  32.  
  33.  
  34. // Generate the secret key specs.
  35. SecretKey skey = kgen.generateKey();
  36. byte[] raw = skey.getEncoded();
  37.  
  38. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  39.  
  40.  
  41.  
  42. // Instantiate the cipher
  43. Cipher cipher = Cipher.getInstance("AES");
  44.  
  45.  
  46.  
  47. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  48. byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());
  49. System.out.println("encrypted string: " + asHex(encrypted));
  50.  
  51. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  52. byte[] original = cipher.doFinal(encrypted);
  53. String originalString = new String(original);
  54. System.out.println("Original string: " + originalString + " " + asHex(original));
  55. }
  56. }

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.

  1. public static String asHex (byte buf[]) {
  2.  
  3. StringBuffer strbuf = new StringBuffer(buf.length * 2);
  4. int i;
  5.  
  6. for (i = 0; i < buf.length; i++) {
  7. if (((int) buf[i] & 0xff) < 0x10)
  8. strbuf.append("0");
  9.  
  10. strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
  11. }
  12.  
  13. return strbuf.toString();
  14. }
Failure is not fatal, but failure to change might be. - John Wooden
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 53
Reputation: neilcoffey will become famous soon enough neilcoffey will become famous soon enough 
Solved Threads: 6
neilcoffey neilcoffey is offline Offline
Junior Poster in Training

Re: AES Encryption Logic

 
1
  #3
May 9th, 2009
Originally Posted by neutralfox View Post
Hello everyone,
What is the key in this program? How can I change the key?
The key is simple a sequence of 16 random bytes created by the KeyGenerator. It's actually the same 16 bytes as returned by getEncoded() -- your raw[] array in this case.

If you want to use some specific sequence of bytes as the key, then you can actually just create a SecretKeySpec object around the byte array-- see this example of AES encryption. Note that if you do generate the key "manually" you need to be slightly careful where the random bytes come from-- it's no good using a weak source such as java.util.Random. SecureRandom is fine for 128-bit keys, though, and is actually what the KeyGenerator uses.

Originally Posted by neutralfox View Post
When the message has been decrypted, what does this "414553207374696c6c20726f636b732121" means?
That's your original message, but with each byte written in hex. For example, 41 in hex is (4*16+1=) 65 in decimal, which is the ASCII code for an 'A'; 45 in hex (4*16+5)=69 is the ASCII code for 'E' etc.
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 123
Reputation: neutralfox is an unknown quantity at this point 
Solved Threads: 0
neutralfox neutralfox is offline Offline
Junior Poster

Re: AES Encryption Logic

 
0
  #4
May 9th, 2009
WoW, thanks a lot for the answers guys. But I am having another problem, I want the user to input a string that can be used as the key but its not working.

  1. byte[] raw = "thekey".getBytes();

but i am having the following errors:
--------------------Configuration: <Default>--------------------
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 6 bytes
at com.sun.crypto.provider.AESCipher.engineGetKeySize(DashoA13*..)
at javax.crypto.Cipher.b(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at AES.main(AES.java:48)

Process completed.

Is there a way for me to allow someone to use a string as the key. If not how can I save the key.

Thanks a lot for your answers guys.

Regards,
Mike.
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 53
Reputation: neilcoffey will become famous soon enough neilcoffey will become famous soon enough 
Solved Threads: 6
neilcoffey neilcoffey is offline Offline
Junior Poster in Training

Re: AES Encryption Logic

 
1
  #5
May 9th, 2009
Yes, the key HAS to be of a certain length. In this case, you're asking for 128-bit encryption, so your key as to be (128/8) = 16 bytes long.

Normally, an encryption key is essentially "random" bytes. You wouldn't just use a string as an encryption key, especially one containing simple words.

If you do need to construct a key from a string, then usually a technique called password-based encryption is used. What this essentially does is to calculate a hash of the password multiple times, to deliberately slow down attempts to guess the key from the password. It also gets round a problem whereby somebody just makes a dictionary of lots of common passwords and their corresponding keys. (It basically does this by appending some random "salt" bytes to the password. The salt bytes are not a secret, but because they're random, there's next-to-zero probability that somebody will have made a dictionary of passwords with THAT particular salt that you've chosen.
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 2
Reputation: sahiltcs is an unknown quantity at this point 
Solved Threads: 0
sahiltcs sahiltcs is offline Offline
Newbie Poster

Re: AES Encryption Logic

 
0
  #6
May 26th, 2009
Hi,

I have been using this code but have come up with a problem.
The encrypt returns a byte array and this is used to decrypt rather
than decrypting the whole encrypted string which is generated.

Can someone help as to how get the original string from the
encrypted string instead of the byte array returned from ashex() method?
I have been trying for 2 days now, but in vain..

Thanks,
Sahil.
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 53
Reputation: neilcoffey will become famous soon enough neilcoffey will become famous soon enough 
Solved Threads: 6
neilcoffey neilcoffey is offline Offline
Junior Poster in Training

Re: AES Encryption Logic

 
0
  #7
May 26th, 2009
Not sure I quite understand the problem, but if you're essentially asking "how do I turn an array of bytes into a string", you pass the array into the constructor of String.
Reply With Quote Quick reply to this message  
Join Date: May 2009
Posts: 2
Reputation: sahiltcs is an unknown quantity at this point 
Solved Threads: 0
sahiltcs sahiltcs is offline Offline
Newbie Poster

Re: AES Encryption Logic

 
0
  #8
May 26th, 2009
Hi,
If we look at the code below:
  1. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  2. byte[] encrypted = cipher.doFinal((args.length == 0 ? message : args[0]).getBytes());
  3. System.out.println("encrypted string: " + asHex(encrypted));
  4.  
  5. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  6. byte[] original = cipher.doFinal(encrypted);
  7. String originalString = new String(original);
  8. System.out.println("Original string: " + originalString + " " + asHex(original));
  9. }
Byte[] array 'encrypted' is generated as the encoded array and then converted through ashex(encrypted) to be printed as a string. This returned string is not stored anywhere for decryption.
But my problem is that we are using the byte[] array 'encrypted' as the input parameter to cipher.dofinal instead of getting a byte array reversely from the string which we just printed. It means that we cannot store this encrypted string and then get an byte[] array which we can pass to the cipher.dofinal for decryption.
Please help as to how to achieve the byte array back from the encrypted string as encryption/decryption in a form of a string would be in a complete cycle.

Thanks,
Sahil.
Last edited by ~s.o.s~; May 27th, 2009 at 12:47 am. Reason: Added code tags, learn to use them.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 1
Reputation: andyc2002 is an unknown quantity at this point 
Solved Threads: 0
andyc2002 andyc2002 is offline Offline
Newbie Poster
 
0
  #9
Oct 26th, 2009
Hi all, I am a newbie on AES.
I know from the AES that it has some procedures such as AddroundKey, SubByes, ShiftColumn.
Would you tell me that where the procedures in the code?
I only see that use the same key and 128 bit size in the code...
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC