3
$\begingroup$

Code:

keygen[keybitlength_] := 
Module[{kbl, kbl1, pPrime, qPrime, nKey, phiOFn, eKey, dKey},
kbl = 2^(keybitlength/2);
kbl1 = 2^(keybitlength/2 - 1);
pPrime = RandomPrime[{kbl1, kbl}];
qPrime = RandomPrime[{kbl1, kbl}];
nKey = pPrime*qPrime;
phiOFn = (pPrime - 1) (qPrime - 1);
While[eKey = RandomPrime[{2, phiOFn}]; ! CoprimeQ[eKey, phiOFn]];
dKey = PowerMod[eKey, -1, phiOFn];
{{eKey, nKey}, {dKey, nKey}}]

The part I don't understand is this (specifically the While statement. to me it seems like it lacks a body?):

While[eKey = RandomPrime[{2, phiOFn}]; ! CoprimeQ[eKey, phiOFn]];
dKey = PowerMod[eKey, -1, phiOFn];
{{eKey, nKey}, {dKey, nKey}}]

While eKey is a random Prime between 2 and phiOFn and not Coprime with phiOFn? To my knowledge eKey and phiOfN should be Coprime for RSA encryption to work.

$\endgroup$
6
$\begingroup$

The While statement can indeed be used with only a condition. Obviously, While[True] is an infinite loop, While[False] immediately stops, but it may make sense when the evaluation of the condition can be different in each cycle. For example

While[n=RandomInteger[{1, 1000}]; Mod[n,100] != 0]; n

computes n until it ends on two zeros.

In your example eKey is computed until eKey and phiOFn are coprime.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.