• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in converting from byte array to String...

 
Murthy Vaddi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9298
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic