The RSA algorithm in “MATHEMATICA”

advertisement
The RSA algorithm in “MATHEMATICA”
The application package “Mathematica" produced by Wolfram Research, is a very powerful
instrument for the numerical and algebraic calculus, able to handle symbols and produce graphs.
This program has a powerful interpreted language too. Below a procedure is given to implement the
RSA algorithm through “Mathematica”.
FirstPrimeAbove[n_] :=Block[{k}, k=n;
While[!PrimeQ[k], k=k+1];
Return[k]]
I load the function that find the prime
number immediately next to n
In[1]:=
Out[1]=
p= FirstPrimeAbove[123456789123456789]
123456789123456823
I produce 2 prime numbers: p and q
In[2]:=
Out[2]=
q=FirstPrimeAbove[987654321987654321]
987654321987654329
In[19]:=
Out[19]=
n=p q
121932631356500565915104429680536767
I calculate their product n.
In[20]:=
z= (p-1) (q-1)
Out[20]= 121932631356500564803993318569425616
I calculate the Eulero function of n
In[21]:=
FactorInteger[%]
Out[21]= {{2,4},{3,1},{7,2},{11,1},{555593,1},
{3366776419,1}, {2519526331601159,1}}
I factorize z to find d, that must be
prime with z.
In[23]:= d=17 13 23 29 31
Out[23]= 4569617
I build d ( public key ) doing the
product of the prime numbers not
belonging to the factorization of z.
In[24]:=GCD[d,z]
Out[24]= 1
I check d and z are prime between
them.
In[25]:= e=PowerMod[d, -1, z]
Out[25]= 50803046124608250832373517313152305
I calculate e ( private key ), that is the
inverse of d in the finite arithmetic
module z.
encode[message_] :=
ToExpression[StringJoin @@ ToString /@
(ToCharacterCode[message]-22 /. 100 ->71) ]
I load the encode and decode functions
that change a message of a text
respectively in a sequence of numbers
and viceversa.
decode [codedmessage_] :=
StringJoin @@
FromCharacterCode /@ (
22+(ToExpression[StringJoin@@#]& /@
Partition[Characters[ToString @
codedmessage],2,2] /.
71 ->100)
In[36]:=encode["Buone Vacanze"]
Out[36]=44958988791064757775887179
I turn the text message in a integer
number.
In[37]:=m=%;
PowerMod[m, d, n]
Out[37]=46153073996292641115718942006658193
I assign the number to m.
I code m with the formula: md mod n
In[38]:=PowerMod[%,e,n]
Out[38]=44958988791064757775887179
I decode the ciphered message with
the formula: mce mod n
In[39]:=decode[%]
Out[39]="Buone Vacanze"
I turn the number just found in the
plain text.
Download