| | |
AES Encryption Logic
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Mar 2009
Posts: 123
Reputation:
Solved Threads: 0
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:
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
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)
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
Last edited by neutralfox; May 8th, 2009 at 6:48 pm.
•
•
•
•
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)
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.
Java Syntax (Toggle Plain Text)
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(); }
Failure is not fatal, but failure to change might be. - John Wooden
•
•
Join Date: Dec 2008
Posts: 53
Reputation:
Solved Threads: 6
•
•
•
•
Hello everyone,
What is the key in this program? How can I change the key?
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.
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.
•
•
Join Date: Mar 2009
Posts: 123
Reputation:
Solved Threads: 0
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.
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.
Java Syntax (Toggle Plain Text)
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.
•
•
Join Date: Dec 2008
Posts: 53
Reputation:
Solved Threads: 6
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.
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.
•
•
Join Date: May 2009
Posts: 2
Reputation:
Solved Threads: 0
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.
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.
•
•
Join Date: Dec 2008
Posts: 53
Reputation:
Solved Threads: 6
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.
•
•
Join Date: May 2009
Posts: 2
Reputation:
Solved Threads: 0
Hi,
If we look at the code below:
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.
If we look at the code below:
Java Syntax (Toggle Plain Text)
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)); }
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.
![]() |
Similar Threads
- Question for the C# Gurus (C#)
- Challenging Question For The Gurus. (C++)
- Saving Data Inside an exe (C++)
- AES Encryption/Decryption Padding is invalid error (C#)
- EOF problem (C++)
Other Threads in the Java Forum
- Previous Thread: Video Segmentation & Summerization
- Next Thread: Problem with LinkedList and AddAll()
| Thread Tools | Search this Thread |
-xlint add android api applet application array arrays automation bi binary blackberry bluetooth chat class classes client code compile compiler component converter database digit eclipse equation error event exception fractal freeze functiontesting game gameprogramming givemetehcodez graphics gui health html hyper ide idea image input int integer j2me java javame javaprojects jetbrains jni jpanel jtable julia learningresources linux list login loop main map method methods mobile myregfun netbeans newbie nonstatic notdisplaying page pearl print problem program programming project qt recursion scanner screen scrollbar server set size sms sort spamblocker sql sqlserver string superclass swing system thread threads tree variablebinding windows xor






