Different results for decodeBase64 in Glassfish and Tomcat

I have a value that i encode with special characters, then encode it again using base64, my development environment is the standard uses Netbeans glassfish server, but site is hosted on Tomcat server, I seem to get different results for exactly the same decryption code/function, it works perfect in netbeans, but on tomcat fails, making my special character decode code fail as characters are not the same

String key = enc_key;

// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");

// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
strDecrypted = new String(cipher.doFinal(Base64.decodeBase64(encrypted.getBytes())));

Any suggestions :-( ?

Jon Skeet
people
quotationmark

You're using the String(byte[]) constructor without specifying an encoding. Don't do that.

Likewise, don't call String.getBytes() without specifying the encoding, either. You're doing that twice in the code you've shown us - and my guess is that you did it when encrypting the data. Always specify the encoding you want to use.

Now we don't know which Base64 class you're using, but I would personally try to find a method which accepts a String to decode to start with - Base64 is logically a byte[] <==> String conversion scheme, so in a decent API you'd have String encode(byte[]) and byte[] decode(String).

people

See more on this question at Stackoverflow