Char Array to Byte array conversion and convert back again to char Arrray

Total Post:28


 1003  View(s)
Rate this:
I want to convert a Java char array to a byte array without creating an intermediate String,since the char array contains a password. I've used a couple of methods, but they all found useless :

char[] password = "password".toCharArray();
byte[] passwordBytes1 = new byte[password.length*2];
byte[] passwordBytes2 = new byte[password.length*2];
for(int i=0; i<password.length; i++) {
    passwordBytes2[2*i] = (byte) ((password[i]&0xFF00)>>8); 
    passwordBytes2[2*i+1] = (byte) (password[i]&0x00FF); 
String passwordAsString = new String(password);
String passwordBytes1AsString = new String(passwordBytes1);
String passwordBytes2AsString = new String(passwordBytes2);
assertTrue(passwordAsString.equals(passwordBytes1) || passwordAsString.equals(passwordBytes2));

The assertion always fails (and, critically, when the code is used in production, the password is rejected), yet the print statements print out password three times. Why are passwordBytes1AsString and passwordBytes2AsString different from passwordAsString, yet appear identical? Am I missing out a null terminator or something? What can I do to make the conversion and unconversion work?
  1. Re: Char Array to Byte array conversion and convert back again to char Arrray

    The problem is your use of the String(byte[]) constructor, which uses the platform default encoding. That's almost never what you should be doing - if you pass in "UTF-16" as the character encoding to work, your tests will probably pass. Currently I suspect that passwordBytes1AsString and passwordBytes2AsString are each 16 characters long, with every other character being U+0000


Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.