I've been doing some research on the RSA encryption system, it's pretty simple to code one using small primes, as there aren't too many possibilities and performance is not a real issue.
Here's how RSA Works:
First, you generate a
n
value, product from 2 primes picked up randomly:n = p * q
Then you need your public key, called e. It can be any number coprime to φ(n):
mcd(φ(n), e) = 1
According to the Euler function,
φ(n) = (p-1)(q-1)
You still need your private key, known as
d
, which is the inverse ofe on modulo **φ(n)
.So
d * e = 1 (mod φ(n))
n
ande
are your public values, whend
is your private key. Nobody should knowp
orq
, as with those values it would be possible to getφ(n)
, and use it to calculated
.
- To encrypt a message, we use
M = m^e (mod n)
, wherem
is the original message, andM
is the encrypted one. So, everybody can send you an encrypted message you can read, by using your public values. - To decrypt a message, you use
d
, as it's the inverse ofe
, soM^d = (m^e)^d = m (mod n)
. The message can be decrypted, but only usingd
.
Knowing this, to encrypt a message we just need to get two random primes, calculate n, e, d,
and make our encryption and decryption methods.
This seems pretty easy in theory, now let's turn this into java code:
I first choose two random primes, the bigger the number, the stronger the encryption. So I'll choose p = 1644623
and q = 1644751
. According to this page, they are primes.
BigInteger p = new BigInteger("1644623");
BigInteger q = new BigInteger("1644751");
Then, on my init method, I initialize n, e
and d:
BigInteger p = new BigInteger("1644623");
BigInteger q = new BigInteger("1644751");
BigInteger n;
BigInteger e;
BigInteger d;
void init() {
n = p.multiply(q);
BigInteger pn = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = n.subtract(pn);
while (!mcd(pn, e).equals(BigInteger.ONE)) {
e = e.add(BigInteger.ONE);
System.out.println(e);
}
d = e.modPow(new BigInteger("-1"), pn);
}
I used BigInteger instead of long, as the values used are extremely big.
In theory, everything works. Practically, pn = 2704992034500
, so checking if mcd(pn, e) = 1
, and if not adding 1 to e
and trying again it's not an option. This program is running since 30 minutes, at an average of 150.000 numbers / second. e = 548151505
and still not found mcd(pn, e) = 1
.
Is there any way to find e
in a reasonable time?