1 byte[] 與 String之間反復(fù)轉(zhuǎn)換導(dǎo)致解密失敗
現(xiàn)象:
String source = "待加密數(shù)據(jù)987654321";
byte[] data = source.getBytes();
byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
System.out.println("加密后的數(shù)據(jù): \r\n" + new String(encodedData));
// 直接解密數(shù)據(jù)
byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
System.out.println("解密后的數(shù)據(jù): \r\n" + new String(decodedData));
// 先將加密的數(shù)據(jù)轉(zhuǎn)換String歉眷,再通過String轉(zhuǎn)換為byte[]果复,再解密
String encodedDataString = new String(encodedData);
// 報(bào)解密錯(cuò)誤
byte[] decodedData2 = RSAUtils.decryptByPrivateKey(encodedDataString.getBytes(), privateKey);
System.out.println("解密后的數(shù)據(jù)2: \r\n" + new String(decodedData2));
分析原因:
1 由于encodedData是經(jīng)過加密處理的數(shù)據(jù),所以里面包含不可見字符键闺,在轉(zhuǎn)換為String的時(shí)候寿烟,會(huì)出現(xiàn)丟失。(根本原因)
2 new String(encodedData)采用的字符編碼有可能是utf-8辛燥,有可能是ASCII筛武,有的將八位解釋為一個(gè)字符缝其,有的將4個(gè)八位解釋為一個(gè)字符。