Problem Encrypting URL using AES

I am successfully encrypting a URL from my client servlet and my serverside servlet handles the request. The code is below.

My problem is that the decrypted URL is not the "id=101&item=22&conf=12234" I am expecting -- in fact, the encrypted part of the URL is changing each time (not what I'd expect because I'm using the same passphrase). I need help understanding AES encryption and possibly an example using a passphrases would be appreciated.

Client servlet code:

String passphrase ="passwordpassword";

byte[] raw = passphrase.getBytes();

SecretKeySpec skeySpec =new SecretKeySpec(raw,"AES");

// Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

String query ="id=101&item=22&conf=12234";

byte[] encrypted = cipher.doFinal(query.getBytes());

String encoded = encodeURL(encrypted.toString());

//GET

response.sendRedirect(DEFAULT_SERVER +"?data=" + encoded);

Serverside servlet code:

String passphrase ="passwordpassword";

byte[] raw = passphrase.getBytes();

SecretKeySpec skeySpec =new SecretKeySpec(raw,"AES");

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

byte[] decrypted = cipher.doFinal(decodedData.getBytes());

byte[] original = cipher.doFinal(decrypted);

String text =new String(original,"utf-8");

out.println(text);

[2050 byte] By [sdfgs3456a] at [2007-11-27 4:43:52]
# 1

>

> Client servlet code:

>String encoded = encodeURL(encrypted.toString());

> Serverside servlet code

>

> byte[] decrypted = cipher.doFinal(decodedData.getBytes());

>

> byte[] original = cipher.doFinal(decrypted);

>

There appear to be a few things wrong with this:

1) I'm not sure what class provides the encodeURL() method, but it doesn't appear to be Base64 encoding (which is how encrypted bytes are typically convereted to for transport).

2) When converting bytes to a String, you should specify the encoding scheme, such as "utf-8" in the getBytes() call, otherwise you run the risk of having a string returned using the encoding scheme for whichever locale the client is set for.

3) You're calling doFinal() twice on the server side. This is guaranteed to give you different data, because you're attemping to decrypt it twice!

When encrypting, transporting and decrypting, make sure you encrypt first, then encode it with something like a Base64-encoder, transport it, decode it using the Base64 decoder, and then decrypt it (by calling doFinal() once) to get the original data. Refer to examples on this forum, in David Hook's book "Beginning Cryptography in Java", or in open-source applications like StrongKey.

arshad.noora at 2007-7-12 9:55:42 > top of Java-index,Security,Cryptography...