943,706 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 14217
  • Java RSS
You are currently viewing page 1 of this multi-page discussion thread
May 8th, 2009
0

AES Encryption Logic

Expand 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:

Java Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 6
Solved Threads: 0
Junior Poster
neutralfox is offline Offline
124 posts
since Mar 2009
May 9th, 2009
0

Re: AES Encryption Logic

Click to Expand / Collapse  Quote originally posted by neutralfox ...
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:

Java Syntax (Toggle Plain Text)
  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.

Java Syntax (Toggle Plain Text)
  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. }
Moderator
Reputation Points: 2136
Solved Threads: 1228
Posting Genius
adatapost is offline Offline
6,527 posts
since Oct 2008
May 9th, 2009
1

Re: AES Encryption Logic

Click to Expand / Collapse  Quote originally posted by neutralfox ...
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.

Click to Expand / Collapse  Quote originally posted by neutralfox ...
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.
Reputation Points: 120
Solved Threads: 7
Junior Poster in Training
neilcoffey is offline Offline
53 posts
since Dec 2008
May 9th, 2009
0

Re: AES Encryption Logic

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.

Java Syntax (Toggle Plain Text)
  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.
Reputation Points: 6
Solved Threads: 0
Junior Poster
neutralfox is offline Offline
124 posts
since Mar 2009
May 9th, 2009
1

Re: AES Encryption Logic

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.
Reputation Points: 120
Solved Threads: 7
Junior Poster in Training
neilcoffey is offline Offline
53 posts
since Dec 2008
May 26th, 2009
0

Re: AES Encryption Logic

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.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
sahiltcs is offline Offline
2 posts
since May 2009
May 26th, 2009
0

Re: AES Encryption Logic

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.
Reputation Points: 120
Solved Threads: 7
Junior Poster in Training
neilcoffey is offline Offline
53 posts
since Dec 2008
May 26th, 2009
0

Re: AES Encryption Logic

Hi,
If we look at the code below:
Java Syntax (Toggle Plain Text)
  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.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
sahiltcs is offline Offline
2 posts
since May 2009
Oct 26th, 2009
0
Re: AES Encryption Logic
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...
Reputation Points: 10
Solved Threads: 0
Newbie Poster
andyc2002 is offline Offline
1 posts
since Oct 2009
Jul 21st, 2010
0
Re: AES Encryption Logic
hello,
plz any one send me the time taken for encryption process
Reputation Points: 10
Solved Threads: 0
Newbie Poster
jaya krish is offline Offline
1 posts
since Jul 2010

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: Need help with heapsort implementation
Next Thread in Java Forum Timeline: How to create a.bak file using Java????





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC