我正在使用这个:
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
为什么这些不一样,这样我就可以取回原来的字节数组?
最佳答案
你所做的实际上是处理 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));
关于Java base64编码,解码产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45249821/