Implementing RSA Encryption in Java
Implementing RSA Encryption in Java
in Java
RSA algorithm
Select two large prime numbers
p, q
Compute
n=pq
(n) = (p-1) (q-1)
Select small odd integer e
relatively prime to (n)
gcd(e, (n) ) = 1
Compute d such that
(d e)% (n) = (e d)% (n) = 1
Public key is (e, n)
Private key is (d, n)
example
p = 11
q = 29
n = 319
(n) = 280
e=3
d = 187
public key
(3, 319)
private key
(187, 319)
Outline of implementation
RSA algorithm for key generation
select two prime numbers p, q
compute n = p q
(n) = (p-1) (q-1)
select small odd integer k such that
gcd(e, (n) ) = 1
compute d such that
(d e)% (n) = 1
RSA algorithm for encryption/decryption
encryption: compute E(M) = (Md)%n
decryption: compute D(M) = (E(M)e)%n
What is a BigInteger?
Java class to represent and perform operations on
integers of arbitrary precision
Provides analogues to Javas primitive integer
operations, e.g.
addition and subtraction
multiplication and division
Along with operations for
modular arithmetic
gcd calculation
generation of primes
Using BigInteger
If we understand what mathematical computations are
involved in the RSA algorithm, we can use Javas
BigInteger methods to perform them
BigInteger Object
Example: randomly generate two BigInteger primes
named p and q of bit length 4 :
/* create a random number generator */
BigInteger p,q;
/*Generate Two Random Prime numbers p,q*/
p= new BigInteger(4, 15, new Random());
q= new BigInteger(4, 15, new Random());
Integer operations
Suppose have declared and assigned values for p and q
and now want to perform integer operations on them
use methods add, subtract, multiply, divide
result of BigInteger operations is a BigInteger
Examples:
BigInteger
BigInteger
BigInteger
BigInteger
w
x
y
z
=
=
=
=
p.add(q);
p.subtract(q);
p.multiply(q);
p.divide(q);
Relative primes
modInverse
Suppose we have declared BigInteger variables x, y
and assigned values to them
We want to find a BigInteger z such that
(x*z)%y =(z*x)%y = 1
that is, we want to find the inverse of x mod y and
assign its value to z