Public Key Cryptology 
The RSA Method

Mathematica code as it appeared in Mathematica in Education, 
Volume 1, No. 1, Fall 1991.

Student Project by
Alan Jaffray
Department of Mathematics
Sonoma State University

MakeCode[i_] :=
  Module[{p,q,b,k},
	e[i] = 1;
    p = Prime[Random[Integer, {10^6,10^8}]];
    q = Prime[Random[Integer, {10^6,10^8}]];
    n[i] = p q;
    While[IntegerQ[(p-1) (q-1) / e[i]],
    	e[i] = Prime[Random[Integer, {10,500}]]];
    b = LCM[p-1, q-1];
    For[k=0; j=0, k==0, j++,
        If[Mod[b j, e[i]] == e[i] - 1, k = j]];
	d[i] = x /.Flatten[Solve[e[i] x == k b + 1, x]];
	{n[i], e[i], d[i]}]

TextToCode[text_,n_] := 
 PartCode[
  EncodeString[
   FillString[text,n]
  ]
 ,n]

PartCode[code_,n_] := 
  Map[ToExpression,Map[JoinChars,Partition[Characters[
    JoinChars[Map[CodeToString,code]]
   ],ChunkLength[n]]]]

JoinChars[chars_] := Apply[StringJoin,chars]

CodeToString[n_] := If[n<10,StringJoin["0",ToString[n]],
							ToString[n]]

ChunkLength[n_] := Floor[Floor[N[Log[10,n]]/2]] * 2

EncodeString[str_] := Map[CharEncode,Characters[str]]

CharEncode[char_] := ToASCII[char] - 31

FillString[str_,n_] :=
	(st1 = str;
	While[Not[IntegerQ[
			   StringLength[st1] / (ChunkLength[n]/2)]],
		  st1 = StringJoin[st1," "]];
	st1)

CodeToText[code_,n_] :=
 Module[{ptext},
  ptext = Map[Characters,Map[ToString,code]];
  Do[While[Length[ptext[[i]]]<ChunkLength[n],
				PrependTo[ptext[[i]],"0"]],
	{i,1,Length[ptext]}];
  ptext = JoinChars[
		   Map[CharDecode,
		    Map[ToExpression,
 		     Map[JoinChars,
 		      Partition[
		       Flatten[ptext],2]]]]];
  ptext]

RSAEncode[ptext_,e_Integer,n_Integer] :=
 						Map[PowerMod[#,e,n]&,ptext]

RSADecode[ctext_,d_Integer,n_Integer] :=
		      		    Map[PowerMod[#,d,n]&,ctext]

SignedRSAEncode[text_,d_,n1_,e_,n2_] :=
 If[n1<n2,
 	RSAEncode[
 		   	RSADecode[
 		   		      TextToCode[text,n1]
 		   	,d,n1]
 	,e,n2],
 	RSADecode[
 		   	RSAEncode[
 		   		      TextToCode[text,n2]
 		   	,e,n2]
 	,d,n1]
 ]

SignedRSADecode[code_,e_,n1_,d_,n2_] :=
  If[n1<n2,
 	CodeToText[RSAEncode[
 		   				 RSADecode[code,d,n2]
 			   ,e,n1],
 	n1],
 	CodeToText[RSADecode[
 		   				 RSAEncode[code,e,n1]
 			   ,d,n2],
 	n2]
  ]