Pergunta

I am trying to encode a string in hex and then convert it again to string. For this purpose I'm using the apache common codec. In particular I have defined the following methods:

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public String toHex(byte[] byteArray){

    return Hex.encodeHexString(byteArray);    

}

public byte[]  fromHex(String hexString){

    byte[] array = null;

    try {
        array = Hex.decodeHex(hexString.toCharArray());
    } catch (DecoderException ex) {
        Logger.getLogger(SecureHash.class.getName()).log(Level.SEVERE, null, ex);
    }

    return array;

}

The strange thing is that I do not get the same initial string when converting back. More strangely, the byte array I get, it's different from the initial byte array of the string. The small test program that I wrote is the following:

    String uno = "uno";
    byte[] uno_bytes = uno.getBytes();

    System.out.println(uno);
    System.out.println(uno_bytes);

    toHex(uno_bytes);
    System.out.println(hexed);

    byte [] arr = fromHex(hexed);
    System.out.println(arr.toString());

An example of output is the following:

uno            #initial string
[B@1afe17b     #byte array of the initial string
756e6f         #string representation of the hex 
[B@34d46a      #byte array of the recovered string

There is also another strange behaviour. The byte array ([B@1afe17b) is not fixed, but is different from run to run of the code, but I cannot understand why.

Foi útil?

Solução

When you print a byte array, the toString() representation does not contain the contents of the array. Instead, it contains a type indicator ([B means byte array) and the hashcode. The hashcode will be different for two distinct byte arrays, even if they contain the same contents. See Object.toString() and Object.hashCode() for further information.

Instead, you maybe want to compare the arrays for equality, using:

System.out.println("Arrays equal: " + Arrays.equals(uno_bytes, arr));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top