# Programming- cryptography

I have defined the following function in Mathematica to get a SET OF m SETS (these sets are the codes {p,q,d,e,n} for the encryption system RSA.):

RSA[m_] :=
Table[
Module[{prime, p, q, k, factors, d, e, n,ans},
prime = RandomPrime[{2, 10^2}, 2]; p = prime[[1]]; q = prime[[2]];
k = (p - 1)*(q - 1) + 1; factors = FactorInteger[k];
d = RandomChoice[factors][[1]]; e = k/d; n = p*q;
ans = {p, q, d, e, n}; ans],
{i, 1, m}];


The problem is that although it is not very probable, these sets can be repeated, and I would like to avoid this case, but I have no idea. I have tried using the Mathematica function Union, in which reapeted sets wouldn't be included, but I don't know how to add more in order to get just m elements (sets).

-
'DeleteDuplicates' ? – Rorschach Feb 22 '14 at 17:33

## 1 Answer

This is a small modification of your code (aiming to achieve what you want). Note:

• you have to deal with p=q (change to RandomSample of the small set of primes you use
• the case when k is prime, e.g. p=5,q=11->k=41. This leads to identity (encryption)...not very useful
• use While to achieve list of desired length

rsamod[m_] :=
Module[{set = {}, lg = 0, p, q, k, d, e},
While[lg < m,
{p, q} = RandomSample[Table[Prime[j], {j, 25}], 2];
k = (p - 1) (q - 1) + 1;
If[Not[PrimeQ@k],
AppendTo[
set, {p, q, d = RandomChoice[Rest@Most@Divisors[k]], k/d, p q}]];
set = Union@set;
lg = Length[set]];
set]


Small testing that has desired properties:

enc[x_, key_] := Mod[x^key[[3]], key[[5]]];
dec[x_, key_] := Mod[x^key[[4]], key[[5]]];
testf[u_, tst_] := # -> {u, enc[u, #], dec[enc[u, #], #]} & /@ tst;


A small test:

testf[2, rsamod[5]]


yields:

{{5, 83, 7, 47, 415} -> {2, 128, 2}, {11, 31, 43, 7, 341} -> {2, 8,
2}, {19, 41, 103, 7, 779} -> {2, 459, 2}, {29, 59, 13, 125,
1711} -> {2, 1348, 2}, {97, 43, 37, 109, 4171} -> {2, 2963, 2}}


where {p,q,d,e,n}->{"plaintext","ciphertext","decoded using RSA key=plaintext"}.

I have tested on larger samples. Other answers may deal with efficiency or issues I have failed to consider.

-