2012-01-12 23 views
1

我想用Base64編碼實現RSA加密。順序是:RSA和Base64編碼太多字節

String -> RSA encrypt -> Base64 encoder -> network -> Base64 decoder* -> RSA decrypt > String 

我有在網絡上發送編碼字符串的Base64和閱讀它作爲對對方的字符串,畢竟Base64是文本,對不對?

現在由於某些原因,當我解碼Base64時,我得到的字節數比我最初發送的要多。

在發送方,我的RSA字符串是512字節。 Base64編碼後的1248長(每次都會有所不同)。 在接收端,我的Base64編碼收到的字符串仍然是1248長,但是當我解碼時,我突然得到了936字節。然後我無法用RSA解密它,因爲ciper.doFinal方法掛起。

我假設這有東西待辦事項與字節​​到Unicode字符串轉換,但我不知道在哪一步發生這種情況,我怎麼能解決它。

發送側代碼:

cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding"); 
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey()); 
byte[] base64byes = loginMessage.getBytes(); 
byte[] cipherData = cipher.doFinal(base64byes); 
System.out.println("RSA: " + cipherData.length); //is 512 long 
//4. Send to scheduler 
Base64PrintWriter base64encoder = new Base64PrintWriter(out); 
base64encoder.writeln(new String(cipherData)); //send string is 1248 long 
base64encoder.flush(); 

接收側代碼:

System.out.println("Base 64: " + encodedChallenge.length()); //1248 long 
byte[] base64Message = encodedChallenge.getBytes(); 
byte[] rsaEncodedMessage = Base64.decode(base64Message); 
System.out.println("RSA: " + rsaEncodedMessage.length); //936 long 
cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding"); 
cipher.init(Cipher.DECRYPT_MODE, privateKey); 
cipherData = cipher.doFinal(rsaEncodedMessage); //hangs up 
System.out.println("Ciper: " + new String(cipherData)); 

P.S. Base64PrintWriter是一個PrintWriter,我已經裝飾過將每個輸出轉換爲base64,然後寫出來。

回答

3

你的編碼有問題。使用基數64而不是基數256意味着所需的8位/ 6位的增加或1/3的類似解碼導致1/4的下降。 1248 * 6/8 = 936

問題似乎是在編碼之前將8位數據轉換爲16位字符串。這需要512 * 16/6字節=〜1365。

您需要一個Base64流,它需要字節而不是字符/字符串。

也許使用Base64.encode()是你需要的?

+1

你是我的英雄:)這確實解決了它。我將Base64PrintWriter更改爲writeln(byte [] b)方法。現在它可以工作。 – lanoxx 2012-01-12 12:19:48

+1

將其更改爲Base64OutputStream,並使Writer作爲父級。相反,創建一個Base64InputStream並讓它使用Reader。即使標準定義將字節轉換爲字節,Base64仍將字節編碼爲字符。那是因爲他們* 8位編碼。您可以將流式傳輸的字節想象成UTF-16編碼的XML。 – 2012-01-13 00:43:32

+0

@owlstead:感謝您的回覆我已經打開了另一個關於這個問題,併發布了我當前的Base64OutputStream解決方案。我很感謝您對這是否正確完成或仍然可以改進的意見? http://stackoverflow.com/questions/8896237/java-base64-how-to-write-a-base64outputstream-class-using-decorator-pattern – lanoxx 2012-01-17 14:27:50