I am new to programming and network security. I am trying to implement RSA algorithm for my classwork but I am not getting correct output so please help me, its not giving the same plain text while decrypting.
following is my code
import java.security.*;
import java.lang.*;
import java.math.*;
public class RSAalgo
{
BigInteger p,q,n,d,e,ph,t;
SecureRandom r;
public RSAalgo()
{
r=new SecureRandom();
p=new BigInteger(512,100,r);
q=new BigInteger(512,100,r);
System.out.println("\n RSA ALGO");
System.out.println("\n Prime No P : "+p.intValue());
System.out.println("\n Prime no Q : "+q.intValue());
n=p.multiply(q);
ph=(p.subtract(new BigInteger("1")));
e = new BigInteger("2");
while((ph.gcd(e).intValue()>1)||(e.compareTo(ph)!=-1))
e=e.add(new BigInteger("1"));
d=e.modInverse(ph);
System.out.println("public key = "+n.intValue()+", "+e.intValue());
System.out.println("Private key = "+n.intValue()+", "+d.intValue());
BigInteger msg=new BigInteger("21");
System.out.println("Message is "+msg);
BigInteger enmsg=encrypt(msg,e,n);
System.out.println("Encrypted message is "+enmsg.intValue());
BigInteger demsg=decrypt(enmsg,d,n);
System.out.println("Decrypted message is "+demsg.intValue());
}
BigInteger encrypt(BigInteger msg,BigInteger e, BigInteger n)
{
return msg.modPow(e,n);
}
BigInteger decrypt(BigInteger msg,BigInteger d, BigInteger n)
{
return msg.modPow(d,n);
}
public static void main(String args[])
{
new RSAalgo();
}
}
input: 21
encrypted msg and decrypted msg are random everytime