简体   繁体   English

Java base64编码,解码产生不同的结果

[英]Java base64 encode, decode yield different results

I'm using this: import com.sun.org.apache.xml.internal.security.utils.Base64; 我正在使用这个: import com.sun.org.apache.xml.internal.security.utils.Base64; to encode/decode Base64 strings and byte arrays to store into a db. 编码/解码Base64字符串和字节数组以存储到数据库中。

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? 为什么这些不一样,以便我可以取回原始的字节数组?

What you are doing is actually dealing with the java pointer instead of the actual bytes. 你正在做的是实际处理java指针而不是实际的字节。 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM