Issue
The following program is part of a larger program demonstrating how public and private keys work but it gives the wrong answer. It gives a result of 123.0 but if you do the calculation in Windows Calculator or in a Python version it gives a result of 99
public class test {
public static void main(String[] args) {
int eData = 176;
int PK = 23;
int N = 187;
double x = Math.pow(eData, PK);
double unenData = x % N;
System.out.println ("Decrypted data :");
System.out.println (unenData);
}
}
The program gives a result of 12.0, I was expecting the result of 99. Thanks in advance for your help.
Solution
BigInteger
To Resolve your error, you should use BigInteger, designed for calculations with very large integers. The BigInteger class in Java provides methods for modular exponentiation and modulus operations that can handle large numbers without losing precision.
You could modify it like this, your output should be 99:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger eData = new BigInteger("176");
BigInteger PK = new BigInteger("23");
BigInteger N = new BigInteger("187");
// Modular exponentiation
BigInteger x = eData.modPow(PK, N);
System.out.println("Decrypted data :");
System.out.println(x);
}
}
Answered By - Adesoji Alu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.