Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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).

share|improve this question
2  
'DeleteDuplicates' ? –  Rorschach Feb 22 at 17:33
add comment

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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