代码之家  ›  专栏  ›  技术社区  ›  frozen

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

  •  1
  • frozen  · 技术社区  · 8 年前

    import com.sun.org.apache.xml.internal.security.utils.Base64; 对Base64字符串和字节数组进行编码/解码以存储到数据库中。

    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);
            }
    

    但是,这会打印出:

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

    为什么这些不一样,这样我就可以得到原始的字节数组?

    1 回复  |  直到 8 年前
        1
  •  4
  •   PotatoManager    8 年前

    实际上,您所做的是处理java指针,而不是实际的字节。

    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));