Parvez Parvez - 1 month ago 16x
Java Question

not getting proper output for RSA algorithm

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.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());

ph=(p.subtract(new BigInteger("1")));

e = new BigInteger("2");

e=e.add(new BigInteger("1"));


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

Thanks in advance


There are more than a few mistakes in your code:

  1. How do you ensure p and q are prime? From javadoc,

BigInteger(int bitLength, int certainty, Random rnd)

Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.

  1. Your public/private key modulus is overflowing. Check there.

Other advice:

  • use meaningful variable names and indent your code. You don't know how hard it is to read and understand your code the way it is.

Also, did you try debugging yourself? I ran the code once and this is the output:


Prime No P : 786207047
Prime no Q : 1415953053
public key = -1680494965, 3
Private key = -1680494965, 524138031
Message is 21
Encrypted message is 9261
Decrypted message is -86438693

And on checking if p was prime:

786207047 is not prime.  It is divisible by 12527.

and everything ends there.