2010-04-22 69 views
6

在.NET中我已生成下列公共密鑰文件:爲什麼我的Java RSA加密給我一個算術異常?

<RSAKeyValue> 
    <Modulus>xTSiS4+I/x9awUXcF66Ffw7tracsQfGCn6g6k/hGkLquHYMFTCYk4mOB5NwLwqczwvl8HkQfDShGcvrm47XHKUzA8iadWdA5n4toBECzRxiCWCHm1KEg59LUD3fxTG5ogGiNxDj9wSguCIzFdUxBYq5ot2J4iLgGu0qShml5vwk=</Modulus> 
    <Exponent>AQAB</Exponent> 
</RSAKeyValue> 

.NET是快樂的使用是正常的方法來進行加密。

我想使用此密鑰對Java中的字符串進行編碼。當我嘗試加密字符串時,我遇到了算術異常。

以下是我使用加密的代碼:

byte[] modulusBytes = Base64.decode(this.getString(R.string.public_key_modulus)); 
byte[] exponentBytes = Base64.decode(this.getString(R.string.public_key_exponent)); 
BigInteger modulus = new BigInteger(modulusBytes);     
BigInteger exponent = new BigInteger(exponentBytes); 

RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent); 
KeyFactory fact = KeyFactory.getInstance("RSA"); 
PublicKey pubKey = fact.generatePublic(rsaPubKey); 

Cipher cipher = Cipher.getInstance("RSA"); 
cipher.init(Cipher.ENCRYPT_MODE, pubKey); 

byte[] cipherData = cipher.doFinal(new String("big kitty dancing").getBytes());  

它是失敗的碼塊的最後一行。

我看了很多例子,這是我能想到的最好的例子。如果不明顯,則R.string.public_key_modulus是Modulus元素中文本的複製/粘貼,同樣適用於指數。

我做錯了什麼?

回答

10

試試這個:

BigInteger modulus = new BigInteger(1, modulusBytes); 
BigInteger exponent = new BigInteger(1, exponentBytes); 

否則,你最終有一個負的模量。 BigInteger(byte[])構造函數假設簽署大端代表。構造函數BigInteger(int, byte[])使用提供的符號位(這裏「1」表示「正」)。

此外,請注意String.getBytes(),它使用平臺「默認字符集」,這取決於運行應用程序的機器的配置。如果要獲得可重現的結果,最好指定一個明確的字符集(例如"UTF-8")。

+0

是的,這很好的解決了,謝謝你的快速反應! – badMonkey 2010-04-23 11:38:30

相關問題