gpt4 book ai didi

java - 将字节数组转换为字符串显示垃圾

转载 作者:行者123 更新时间:2023-12-02 05:18:33 25 4
gpt4 key购买 nike

我在使用 new String() 方法将字节数组转换为字符串时遇到问题。即使进行了编码,输出仍然是输出垃圾。

我正在研究 UDP 套接字编程,并且能够在主机/客户端之间发送加密和解密的消息。我想做的是使用接受字符串的 SHA-1 将字节形式的解密消息转换为十六进制函数的字符串。

    //received encrypted data from client
byte[] cipherKB = new byte[8];
cipherKB = receivePacket.getData();
System.out.println(Arrays.toString(cipherKB)); //this output correct data from byte array

//contents of cipherKB [-36, 120, 90, 1, -51, 99, 27, 97]

//decrypt the above message using "decrypt" method
byte[] KB = new byte[8];
KB = r.decrypt(cipherKB); // r is an object
System.out.println(Arrays.toString(KB)); //this output correct data from byte array

//contents of KB [82, -127, 11, -40, -60, 81, 12, 65]

String KBString = new String (KB,"UTF-8");
System.out.println(KBString); //this is giving me garbage message when I output in console

System.out.println("KB.toString(): output " + KB.toString());

//KB.toString(): output [B@578088c0
.....
}
<小时/>
//Decrypt function



private final static byte[] S = new byte[256];
private final byte[] T = new byte[256];
private final int keylen;

public static byte[] encrypt(final byte[] plaintext) {
final byte[] ciphertext = new byte[plaintext.length];
int i = 0, j = 0, k, t;
byte tmp;
for (int counter = 0; counter < plaintext.length; counter++) {
i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
tmp = S[j];
S[j] = S[i];
S[i] = tmp;
t = (S[i] + S[j]) & 0xFF;
k = S[t];
ciphertext[counter] = (byte) (plaintext[counter] ^ k);
}
return ciphertext;
}

public static byte[] decrypt(final byte[] ciphertext) {
return encrypt(ciphertext);
}
}

输出数据以显示加密正在运行:

//HOST - Alice

Alice Random KA:[45, 58, -4, 93, -1, -127, 127, 20]

Alice Random KA in string:[B@6791d8c1 //output of String KAString = new String (KA);

Alice encrypted KA sent to Client: [-63, 81, -91, 119, 124, -24, 86, 41]

Received Bob's KB: [16, 103, 39, -13, 46, -120, 115, -116] //this is same as Bob's encrypted KB below

Decrypted Bob's KB: [-98, -98, 118, 42, 39, -70, 100, -84] //same as Bob's Random KB generated

//CLIENT - Bob

Received Alice's encrypted KA: [-63, 81, -91, 119, 124, -24, 86, 41]

Decrypted Alice's KA: [45, 58, -4, 93, -1, -127, 127, 20] //this is same as Alice's Random KA above

Bob's Random KB:[-98, -98, 118, 42, 39, -70, 100, -84]

Bob's encrypted KB: [16, 103, 39, -13, 46, -120, 115, -116]

最佳答案

您当然意识到,[B@6791d8c1 只是一个没有自己版本的对象的默认 toString。并且 [45, 58, -4, 93, -1, -127, 127, 20] (加密前的原始数据)是“-:]” - 不是真正有效的字符数据,所以人们会认为它看起来像“垃圾”。

关于java - 将字节数组转换为字符串显示垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com