I'm working on an RSA algorithm for school, and I need to generate n to be a certain length (300 digits to be exact). I found that the length was different when I called it again later. Let me post a condensed version of my program that displays my problem.
import java.math.BigInteger;
import java.util.Random;
public class post {
private static BigInteger n;
private static BigInteger phi;
public static BigInteger generateN (int bitLength) {
BigInteger p;
BigInteger q;
BigInteger pq;
int pqLength;
String pqCheck = "255";
Random r = new Random();
p = new BigInteger ( BigInteger.probablePrime ( bitLength, r ).toString() );
q = new BigInteger ( BigInteger.probablePrime ( bitLength, r ).toString() );
phi = (p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)));
pq = new BigInteger ( p.multiply ( q ).toString() );
pqLength = pq.toString().length();
System.out.println ( "pq's initial length = " + pqLength );
if ( pqLength == 300 && pq.toString().substring(0,3).compareTo(pqCheck) > 0 ) {
pqLength = pq.toString().length();
System.out.println("pq's final length = " + pq.toString().length());
System.out.println ( "pq's length is correct! ");
return pq;
}
else if ( pqLength > 300 ) {
System.out.println ( "pq's length = " + pqLength + ".");
System.out.println("Adjusting pq's size . . .");
generateN ( bitLength - 1 );
}
else if ( pqLength < 300 ) {
System.out.println ( "pq's length = " + pqLength + ".");
System.out.println("Adjusting pq's size . . .");
generateN ( bitLength + 1 );
}
return pq;
}
public static void main (String[] args) {
n = generateN(500);
System.out.println("n = " + n);
System.out.println("n length: " + n.toString().length());
}
}
Here's the output:
pq's initial length = 301 pq's length = 301. Adjusting pq's size . . . pq's initial length = 301 pq's length = 301. Adjusting pq's size . . . pq's initial length = 300 pq's final length = 300 pq's length is correct! n = 8329309603832552605779583004111676117460428566431326966642828167503750649563 80535960505216672704803077357421811675713198519942740954310354688260927978852650 64394907705824412066832605959708311583720908765772363409810060959977345989655475 43031211942699693596749477723293046696554262266476407957866108867 n length: 301
As you can see, it says that pq's length is 300, but n's length is 301. The numbers are clearly not identical, and I don't know why.
Where am I going wrong in this? Why is n not the value I assume that I assign it?
Thanks for the help.


Sign In
Create Account

Back to top









