简体   繁体   English

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

[英]How to convert key byte array to string and vice versa

I am generating two keys: 1) Public key and 2) Private key, both are stored as byte array, I need to convert these two keys into string and send it to receiver side and receiver will convert string to byte array. 我正在生成两个密钥:1)公共密钥和2)私有密钥,它们都存储为字节数组,我需要将这两个密钥转换为字符串并将其发送到接收方,接收方会将字符串转换为字节数组。 But somehow it gives different key bytes after converting string to byte array 但是以某种方式将字符串转换为字节数组后会给出不同的关键字节

coding: 编码:

 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

output : 输出:

在此处输入图片说明

Writing strings with arbitrary bytes invokes the default character encoding. 用任意字节写字符串会调用默认的字符编码。 Since some byte sequences cannot be represented in the encoding as characters, they'll get lost in the conversion. 由于某些字节序列无法在编码中表示为字符,因此它们会在转换中丢失。 I would recommend encoding the bytes in Base64 if you need them converted to a string. 如果需要将字节转换为字符串,我建议在Base64中对字节进行编码。 See https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html 参见https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html

The problem is here... 问题在这里...

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

You are converting string from byte[].. it will add some extra character... so its batter to transfer this kind of information as byte[] itself.. or you can try base64 for encoding and decoding keys... it may help. 您正在从byte []转换字符串..它会添加一些额外的字符...,以便将其作为字节[]本身来传输此类信息..或者您可以尝试使用base64来编码和解码密钥...它可能救命。

byte[] (or any other arrays) don't have an overriden toString, so what they show you is just the object identifier itself. byte[] (或任何其他数组)没有重写的toString,因此它们向您显示的只是对象标识符本身。 Therefore, two different arrays will never show the same string representation. 因此,两个不同的数组将永远不会显示相同的字符串表示形式。

To print the array contents proper, use Arrays.toString() 要正确打印数组内容,请使用Arrays.toString()

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

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