如何将关键字节数组转换为字符串,反之亦然

时间:2016-07-29 11:23:38

标签: java string byte bytearray type-conversion

我生成两个密钥:1)公钥和2)私钥,两者都存储为字节数组, 我需要将这两个键转换为字符串并将其发送到接收方,接收方将字符串转换为字节数组。但不知何故,它在将字符串转换为字节数组后给出了不同的关键字节

编码:

 System.out.println("certificate insertionSuccessful."+certPojo.getUser_public_key()+", "+certPojo.getUser_private_key());

String str1 = new String(certPojo.getUser_public_key());
String str2 = new String(certPojo.getUser_private_key());

System.out.println("publickey===>"+str1);
System.out.println("privatekey===>"+str2);

byte[] bytes1 = str1.getBytes();
byte[] bytes2 = str2.getBytes();

System.out.println("Text [Byte Format] : " + bytes1);
System.out.println("Text [Byte Format] : " + bytes2);

I also tried using UTF-8 but nothing works

输出:

enter image description here

3 个答案:

答案 0 :(得分:0)

使用任意字节编写字符串会调用默认字符编码。由于某些字节序列无法在编码中表示为字符,因此它们会在转换中丢失。如果你需要将它们转换为字符串,我建议在Base64中编码字节。见https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

答案 1 :(得分:0)

问题出在这里......

String str1 = new String(certPojo.getUser_public_key());
String str2 = new String(certPojo.getUser_private_key());

你正在从byte []转换字符串..它会添加一些额外的字符...所以它的电池将这种信息作为byte []本身传输..或者你可以尝试使用base64来编码和解码密钥..它可能有所帮助。

答案 2 :(得分:0)

byte[](或任何其他数组)没有覆盖toString,因此它们显示的只是对象标识符本身。因此,两个不同的数组永远不会显示相同的字符串表示。

要正确打印数组内容,请使用Arrays.toString()