Your problem is that you cannot construct a UTF-16 string (or any other encoding) from an arbitrary byte array (see UTF-16 on Wikipedia ). However, you decide to serialize and deserialize the encrypted byte array without any loss, to, say, save it and use it later. Here's the modified client code, which should give you an idea of what is actually happening with byte arrays:
public static void main(String[] args) throws Exception { String toEncrypt = "FOOBAR"; NewEncrypter encrypter = new NewEncrypter(); byte[] encryptedByteArray = encrypter.encrypt(toEncrypt); System.out.println("encryptedByteArray:" + Arrays.toString(encryptedByteArray)); String decoded = new String(encryptedByteArray, "UTF-16"); System.out.println("decoded:" + decoded); byte[] encoded = decoded.getBytes("UTF-16"); System.out.println("encoded:" + Arrays.toString(encoded)); String decryptedText = encrypter.decrypt(encryptedByteArray);
This is the conclusion:
encryptedByteArray:[90, -40, -39, -56, -90, 51, 96, 95, -65, -54, -61, 51, 6, 15, -114, 88] decoded:<some garbage> encoded:[-2, -1, 90, -40, -1, -3, 96, 95, -65, -54, -61, 51, 6, 15, -114, 88] decryptedText:FOOBAR
decryptedText correct if it is restored from the original encryptedByteArray . Note that the encoded value does not match the encryptedByteArray due to data loss during the conversion byte[] -> String("UTF-16")->byte[] .
Alexander Pavlov Feb 01 '12 at 15:50 2012-02-01 15:50
source share