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

Recommended Answers

All 13 Replies

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();
     }

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.

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.

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.

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.

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.

commented: Very informative. +4

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.

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.

Hi,
If we look at the code below:

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));
     }

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.

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...

hello,
plz any one send me the time taken for encryption process

The time taken depends upon the the code you are using and also the programming language you have implemented..for more details go to this link.

commented: zombie master -3

Its working fine But.. The Generated Encrypted was every time generating new keys for the Given Same Value. which is gud for save but Want to compare a string with Encripted means its not working coz every time the Key is Random one. how to get the proper code for given same string shld return same value.

commented: zombie master -3

Can anyone suggest me how to do the AES ENCRYPTION of 16byte hex random number ?? and also how to generate a 16byte hex number randomly .

DaniWeb Member Rules (which you agreed to when you signed up) include:
"Do not hijack old threads by posting a new question as a reply to an old one"
http://www.daniweb.com/community/rules
Please start your own new thread for your question

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.