我有一個問題,使用新的String()方法將字節數組轉換爲字符串。 即使使用編碼,輸出仍是輸出垃圾。轉換字節數組爲字符串顯示垃圾
我正在研究UDP套接字編程,並能夠在主機/客戶端之間發送加密和解密的消息。我想要做的是將解密的消息以字節轉換爲使用SHA-1的十六進制函數的字符串,該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 [[email protected]
.....
}
//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:[[email protected] //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]
加密方法是什麼S數組? – SMA 2014-11-02 12:38:12
@almasshaikh S是字節數組。上面更新。 – user23 2014-11-02 12:55:06
那麼,你的字節數組是什麼?我猜他們不是合法的Unicode字符。 – 2014-11-02 12:58:26