Sei sulla pagina 1di 13

RSA Implementation w/ Java

Greg Macko
RSA Key Generation
1) Choose two large prime numbers p and q such that p != q,
randomly and independently of each other
2) Compute n = pq
3) Compute phi(n) = (p - 1)(q - 1)
4) Choose an integer e such that 1<e<phi(n) which is coprime to
phi(n)
5) Compute d such that de is congruent to 1 (mod phi(n))

Note:1) probabilistically test for prime numbers using Fermat’s


little theorem
2) steps 4 and 5 can be done using extended Euclidean
algorithm
Key Components
 Public Key:
 n and e

 Private Key:
 n and d
Encrypting Messages
 Break file into blocks (messages)
 Convert message into number using
agree-upon protocol

ciphertext = messagee mod n
 Repeat for each block and output
ciphertext to new file
Decrypting Messages
 Read in blocks of ciphertext from file

message = ciphertextd mod n
 Convert message (which is a number)
back to text
 Repeat for each block in encrypted file
Java BigIntegers
 Immutable arbitrary-precision integers. All operations
behave as if BigIntegers were represented in two's-
complement notation (like Java's primitive integer
types). BigInteger provides analogues to all of Java's
primitive integer operators, and all relevant methods
from java.lang.Math. Additionally, BigInteger provides
operations for modular arithmetic, GCD calculation,
primality testing, prime generation, bit manipulation,
and a few other miscellaneous operations.
Java RSA Key Generation
// generate keys with prime probability of 100%
p = new BigInteger(bitLength/2, 100, sr);
q = new BigInteger(bitLength/2, 100, sr);

// n=pq
n = p.multiply(q);

//phi(n) = (p-1)(q-1)
phi = p.subtract(BigInteger.ONE).multiply
(q.subtract(BigInteger.ONE));
Java RSA Key Generation
// calculate e such that 1 < e < phi(n) which is coprime to
phi(n)
e = new BigInteger("2");
while(true) {
if(phi.gcd(e).compareTo(BigInteger.ONE) == 0)
break;
else e = e.add(BigInteger.ONE);
}
// calculate d such that de is congruent to 1 mod phi(n)
d = e.modInverse(phi);
Java RSA Encryption
// ciphertext = message ^ e mod n

Public static BigInteger encrypt(BigInteger bi)


{
return bi.modPow(e,n);
}
Java RSA Decryption
// message = ciphertext ^ d mod n

public static BigInteger decrypt(BigInteger bi)


{
return bi.modPow(d,n);
}
Convert message to number
 Keep running total
 Read individual character
 Convert to ASCII value
 Shift total left 8 bits
 Add next character to total
 repeat
Convert number to message
 Copy original number
 Shift copy right so only leftmost 8 bits
remain
 Convert to character
 Reset leftmost 8 bits of original number
 repeat
Demo

 Questions?

Potrebbero piacerti anche