跨服務傳遞加密數據,本地驗證通過,遠端卻失敗。根因在於 byte[] 與 String 互轉時,預設 UTF-8 將單字節誤判為多字節字符,導致數據損壞。
byte[] cipher。String s = new String(cipher); 或 new String(cipher, "UTF-8")。String。byte[] recv = s.getBytes("UTF-8") → 數據長度、內容已變,解密/驗簽必敗。// 加密端
String encoded = Base64.getEncoder().encodeToString(cipher);
// 傳輸 encoded 字符串
// 解密端
byte[] cipher = Base64.getDecoder().decode(encoded);
// 加密端
String hex = bytesToHex(cipher); // 自行實現或用 Apache Commons Codec
// 解密端
byte[] cipher = hexToBytes(hex);
加密輸出的 byte[] 必須經過「二進制安全」編碼才能當作字符串傳輸。UTF-8 是字符編碼,不適合任意二進制數據。
// 簽名驗證
boolean ok = RSAUtils.verify(plainBytes, publicKey, signatureBytes);
// 解密
byte[] plain = RSAUtils.decrypt(cipherBytes, privateKey);
修正編碼後,控制台打印的 Arrays.equals(localBytes, remoteBytes) 應為 true,驗證與解密均恢復正常。