[英]String of byte array to byte array (rsa and java)
我正在處理 web 服務,我想將字節數組作為字符串發送,然后獲取原始字節數組。
我再解釋一下,我的服務器端有加密消息的作用,所以我有一個字節數組。
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE,clefPrivee);
byte[] cipherText= cipher.doFinal(msgEnOctets);
然后發送這個加密的消息,我把它作為一個字符串發送,因為我發送了一個完整的數據幀
代碼:
cipherText.toString();
所以我將數組作為一個字符串,但沒有任何改變。
我怎樣才能找回我的原畫?
謝謝
發送字節數組的一種常見方法是在發送之前將其編碼為 Base64,另一方面在接收字符串時必須將其解碼為 Base64 以獲得原始字節數組。 例如:
發件人:
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(cipher.ENCRYPT_MODE,clefPrivee);
byte[] cipherText= cipher.doFinal(msgEnOctets);
return Base64.getEncoder().encodeToString(cipherText);
接收者:
public void getMessage(String message) {
byte[] decodeMessage = Base64.getDecoder().decode(message);
//...
}
請不要使用來自@andy jason ( https://stackoverflow.com/a/63489562/8166854 ) 的轉換作為字節數組(尤其是與用於加密的數據一起使用時)無法轉換為字符串,反之亦然字符串(字節,字符集)。
字節數組 -> 字符串 -> 字節數組轉換的一種方法是使用 Base64 編碼:
結果:
ByteToString and reverse test
bytes: ee99c01c47185dbd6b62dd9bcfed94d7
method as by comment andy jason
s: ��G]�kbݛ���
tab: efbfbdefbfbd1c47185defbfbd6b62dd9befbfbdefbfbdefbfbd
bytes equal to tab: false
method with base64
s2: 7pnAHEcYXb1rYt2bz+2U1w==
tab2: ee99c01c47185dbd6b62dd9bcfed94d7
bytes equal to tab2: true
代碼:
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
public class ByteToString {
public static void main(String[] args) {
System.out.println("https://stackoverflow.com/questions/63489517/string-of-byte-array-to-byte-array-rsa-and-java");
System.out.println("ByteToString and reverse test");
byte[] bytes = new byte[16];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(bytes);
System.out.println("bytes: " + bytesToHex(bytes));
// method by andy jason
System.out.println("\nmethod as by comment andy jason");
Charset charset = StandardCharsets.UTF_8;
String s = new String(bytes, charset);
System.out.println("s: " + s);
byte [] tab = s.getBytes (charset);
System.out.println("tab: " + bytesToHex(tab));
System.out.println("bytes equal to tab: " + Arrays.equals(bytes, tab));
// method with base64
System.out.println("\nmethod with base64");
String s2 = Base64.getEncoder().encodeToString(bytes);
System.out.println("s2: " + s2);
byte[] tab2 = Base64.getDecoder().decode(s2);
System.out.println("tab2: " + bytesToHex(tab2));
System.out.println("bytes equal to tab2: " + Arrays.equals(bytes, tab2));
}
private static String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}
如果要將字節數組可逆地轉換為 String,則必須使用需要字節數組的 String 構造函數:
String s = new String(bytes, charset);
然后要找到你的字節數組,你必須小心使用相同的字符集:
byte [] tab = s.getBytes (charset);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.