aspose file tools*
The moose likes Java in General and the fly likes Problem in converting from byte array to String... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in converting from byte array to String..." Watch "Problem in converting from byte array to String..." New topic
Author

Problem in converting from byte array to String...

Murthy Vaddi
Greenhorn

Joined: May 01, 2005
Posts: 1
Heloo All,
I am getting a byte array when I encrypt using an AES algorithm. I converted the byte array to a String using
new String(byte[] byteArray, String charsetName)

constructor. When I try to decrypt the encrypted String I tried to get the byte[] again using
String.getBytes(charsetName

), I am not getting the same byte array. I am using charsetName "UTF-16LE". Because of this decryption is not working. The following is the code that I am talking about:


public class TestByteArrayToString {
private static String charsetName = "UTF-16LE";

public static void main(String[] args) {
try{
byte[] bytes = { 75, -88, 73, -24,
-116, -28, -79, 25,
31, 97, 21, 87,
-53, 121, 75, -36};

for(int i=0; i<bytes.length; i++) {
System.out.println("byte :" + bytes[i]);
}
String bytesStr = new String(bytes, charsetName);
byte[] byteArray = bytesStr.getBytes(charsetName);
for(int i=0; i<byteArray.length; i++) {
System.out.println("byteArray :" + byteArray[i]);
}
System.out.println("bytesStr : " + bytesStr);
} catch(Exception e) {
e.printStackTrace();
}
}
}


In the above code I am not getting the same original byte array after converting into String. If I use charsetBane "UTF-16BE", I am getting the original bytes. But in my program I am always using UTF-16LE in all the places. Is there any error or known bug with java unicode encoding using UTF-16LE. Please help me if anyone faced similar kind of issue and I really appreciate it.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8927
    
    9

Originally posted by Murthy Vaddi:
I converted the byte array to a String using
new String(byte[] byteArray, String charsetName)constructor. When I try to decrypt the encrypted String I tried to get the byte[] again using
String.getBytes(charsetName), I am not getting the same byte array.


Correct. A byte array of binary data generated by the AES encryption algorithm is not the same thing as a byte array of UTF-16LE encoded characters. Some of the bytes will be trimmed to fit the UTF-16LE codepage and you end up with garbage.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in converting from byte array to String...