41 static private long n;
45 static private long d;
49 static private long e;
80 private long egcd(
long a,
long b,
long[]last) {
93 x = last[0] - quotient * x;
96 y = last[1] - quotient * y;
130 private long modinv2(
long a,
long b,
long c) {
135 return (c / a) % (b / a);
137 return (
modinv2(r, a, -c) * b + c) / a%b;
154 while ( drev != 0 ) {
155 e = (drev & 1)==1 ? c : 1;
185 long phi = (p-1)*(q-1);
187 if (
d==0)
return phi;
213 public static void main ( String[] args ) {
217 if (args.length < 3) {
218 System.out.print ( String.format(
"usage: %s <number1> <number2> <prime size(small=0,medium=1,large=2)>\n",
"rsa"));
222 a = Integer.parseInt(args[0]);
223 b = Integer.parseInt(args[1]);
224 psize = Integer.parseInt(args[2]);
228 long[] xy =
new long[2];
229 long gcd = r.
egcd(a, b, xy);
230 long x = xy[0];
long y = xy[1];
231 System.out.print(String.format(
"The GCD of %d and %d is %d\n", a, b, gcd));
232 System.out.print(String.format(
"%d * %d + %d * %d = %d\n", a, x, b, y, gcd));
233 System.out.print(String.format(
"The modular inverse of %d and %d is %d\n", a, b, r.
modinv(a,b)));
246 if (phi > 0) System.out.print (String.format(
"gcd(%d,%d) is not 1 (modular inverse does not exist)", r.
e, phi));
248 System.out.print(String.format(
"Public key is: n = %d and e = %d\n", r.
n, r.
e));
249 System.out.print(String.format(
"Private key is: n = %d and d = %d\n", r.
n, r.
d));
253 while ((tnumber >=
n) || (tnumber < tmin)) {
254 System.out.print (String.format(
"Enter number to be encrypted (%d <= n <= %d): ", tmin,
n-1));
255 tnumber = Integer.parseInt(System.console().readLine());
261 System.out.print(String.format(
"%d encrypted is: %d\n", tnumber, c));
262 System.out.print(String.format(
"%d decrypted is: %d\n", c, m));