Search code examples
javastringencodingbase64decoding

Java base64 encode, decode yield different results


I'm using this: import com.sun.org.apache.xml.internal.security.utils.Base64; to encode/decode Base64 strings and byte arrays to store into a db.

I'm testing out encoding and decoding to see if I can get back the original string:

SecureRandom srand = new SecureRandom();
        byte[] randomSalt = new byte[64];
        srand.nextBytes(randomSalt);
        System.out.println("rand salt bytes: " + randomSalt); // first line
        String salt = Base64.encode(randomSalt);
        try {
            System.out.println(Base64.decode(salt)); // second line
        }catch(Base64DecodingException e){
            System.out.println(e);
        }

However, this prints out:

rand salt bytes: [B@68286c59
[B@44d01f20

Why are these not the same, so that I can get back the original byte array?


Solution

  • What you are doing is actually dealing with the java pointer instead of the actual bytes. This is the correct way to implement

    byte[]   bytesEncoded = Base64.encodeBase64(str .getBytes());
    System.out.println("ecncoded value is " + new String(bytesEncoded ));
    
    // Decode data on other side, by processing encoded data
    byte[] valueDecoded= Base64.decodeBase64(bytesEncoded );
    System.out.println("Decoded value is " + new String(valueDecoded));