Search code examples
javaarraysbytebufferjava-securitycharbuffer

Java Conversion from byte[] to char[]


I have wrote a simple snippet in which I try to convert (maybe) a byte array in char array e vice versa. There are a lot of examples on the Net but this is for me the simplest way to do it. I need to use array and not strings because its content is a password field to manage.

So I ask you, is this snippet correct?

private static char[] fromByteToCharArrayConverter(byte[] byteArray){
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    clearArray(byteArray);
    CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer);

    char[] charArray = new char[charBuffer.remaining()];
    charBuffer.get(charArray);  

    return charArray;
}

private static byte[] fromCharToByteArray(char[] charArray){
    CharBuffer charBuffer = CharBuffer.wrap(charArray);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);

    byte[] byteArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(byteArray);

    return byteArray;
}

Thanks


Solution

  • No, that won't work for (at least) the following reason:

    ByteBuffer buffer = ByteBuffer.wrap(byteArray);  // Wrap the array
    clearArray(byteArray);  // Clear the array -> ByteBuffer cleared too