We have been given an assignment part of which requires us to generate a public private key pair. These do not need to be particularly secure, as it is just for demonstration of the concept.
We can not use any sort of cryptography libraries or external tools.
How would I go about generating these?
Edit: Found a pretty nice explanation of RSA here: https://www.educative.io/edpresso/what-is-the-rsa-algorithm
CodePudding user response:
I use JShell to demonstrate the basic public-private key generation just using Java's BigInteger
:
jshell> import java.math.BigInteger;
jshell> var rnd = new java.security.SecureRandom();
rnd ==> Hash_DRBG,SHA-256,128,reseed_only
First we need 2 primes
jshell> var p1 = BigInteger.probablePrime(512, rnd);
p1 ==> 1176110601168217581401499298469596353224364190716 ... 72507270343325790065694831
jshell> var p2 = BigInteger.probablePrime(512, rnd);
p2 ==> 1001341560055006431459083188828513502474297271020 ... 34378293673605844490263567
Next we calculate the public key. 0x10001 is a common exponent for the public key.
jshell> var n = p1.multiply(p2);
n ==> 1177688424171014462551464978852125044384293220079 ... 24824881562893076179522177
jshell> var e = BigInteger.valueOf(0x10001);
e ==> 65537
The public key is e
and n
.
Now the private part.
jshell> var phi = p1.subtract(BigInteger.ONE).multiply(p2.subtract(BigInteger.ONE));
phi ==> 1177688424171014462551464978852125044384293220079 ... 17939317545961441623563780
jshell> var d = e.modInverse(phi);
d ==> 7023685818262702180949167670691999860354377649273 ... 38390163809778429090416313
The private key is now d
and n
.
Let's test it:
jshell> var secret = BigInteger.valueOf(1337);
secret ==> 1337
jshell> var enc = secret.modPow(e, n);
enc ==> 1059982071031392497566614763259148320406936402012 ... 39171914529632475117049800
jshell> enc.modPow(d, n);
$11 ==> 1337
We could send enc
over the wire, and nobody could decrypt it without the knowledge of the private key. Well, at least in theory. In practice, you should pad your messages.