Search code examples
javaintegerbigdecimalmodulusalgebra

Modulus with big numbers in java


I'm programming an RSA decryption prototype in java. It's just for showing how it works for school which is why I try to keep it as simple as possible. But when I get to the decryption part I have to use the formula:

c = m^e % n.

For testing purposes I tried to do that with m = "1010" (because I get it as a String from my program), e = 55, n = 361. This should give me 345 as c(tested in windows calculator). The results I'm getting are:

Math.pow(Integer.parseInt("1010"), 55) % 361 // 115.0

BigDecimal b = BigDecimal.valueOf(Math.pow(Integer.parseInt("1010"),55));

(b.remainder(BigDecimal.valueOf(361))).doubleValue() // 300.0

Math.pow(Integer.parseInt("1010"), 55) % 361 //  340

Please tell me where I am wrong or how I can fix this. Thanks in advance.


Solution

  • I suggest to use BigInteger, in this case, it will be useful knowing that the exponentiations may result ( at most of the times) an overflow. Here I came with an application of your example using BigInteger, I hope it will help :

     BigInteger m  = BigInteger.valueOf(1010);
     BigInteger e  = BigInteger.valueOf(55);
     BigInteger n  = BigInteger.valueOf(361);
     BigInteger c = m.modPow(e,n);
     System.out.println(c);