Why does my java RSA encryption give me an arithmetic exception?
Yes Net, I generated the following public key file:
<RSAKeyValue> <Modulus>xTSiS4+I/x9awUXcF66Ffw7tracsQfGCn6g6k/hGkLquHYMFTCYk4mOB5NwLwqczwvl8HkQfDShGcvrm47XHKUzA8iadWdA5n4toBECzRxiCWCHm1KEg59LUD3fxTG5ogGiNxDj9wSguCIzFdUxBYq5ot2J4iLgGu0qShml5vwk=</Modulus> <Exponent>AQAB</Exponent> </RSAKeyValue>
. Net is happy to use its conventional methods for encryption
I'm trying to encode strings in Java using this key When I tried to encrypt a string, I encountered an arithmetic exception
Here is the code I used to encrypt:
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() );
It is the last line failure in the code block
I have seen many examples, which is the best example I can think of If not obvious, r.string public_ key_ Modulus is the copy / paste of text in modulus element, which is also applicable to index
What did I do wrong?
resolvent
Solution
Try this:
BigInteger modulus = new BigInteger(1,modulusBytes ); BigInteger exponent = new BigInteger(1,exponentBytes);
Otherwise you end up with a negative modulus The BigInteger (byte []) constructor assumes a signed big endian representation The BigInteger (int, byte []) constructor uses the supplied sign bit (where "1" means "positive")
In addition, be wary of string GetBytes (), which uses the platform "default charset", depends on the configuration of the machine running the application If you want reproducible results, it is best to specify an explicit character set (for example, "UTF-8")
The above is collected by the programming house for you. Why does my java RSA encryption give me an arithmetic exception? I hope this article can help you solve why my java RSA encryption will give me an arithmetic exception? Program development problems encountered.
If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.