In[10]:=
ToCharacterCode[ "abcdefghijklmnopqrstuvwxyz"]
Out[10]
We see that the codes are consecutive. This will make the computation simpler.
In[11]:=
In[12]:=
Out[12]
In[13]:=
Out[13]
The string should have no punctuation other than spaces. If you want to allow
punctuation, then
In[14]:=
Out[14]
In[15]:=
Out[15]
In[16]:=
Up to String Manipulation
If we subtract 97 from the code, and then add number modulo 26, then add 97 to
the number
and convert it back to a string, then we will have the cipher text. This is
done in the
following procedure.
shiftcipher[ s_, k_]:= Module[ {s1},
s1=StringReplace[
ToLowerCase[s], { " "->""}];
l=ToCharacterCode[ s1]-97;
l=Mod[ l+k,26];
s1=FromCharacterCode[l+97];
Return[s1]]
shiftcipher[ "abc",3]
shiftcipher[ "I came I saw I conquered", 7]
the StringReplace command in the procedure needs to modified appropriately.
Since
conversion of a string to numeric form is common, we will write a separate
function for this.
ToNumericForm[m_String]:= Module[ {text},
text=ToLowerCase[m];
If[Length[StringPosition[text," "]]>=1,
text= StringReplace[text," "->""]];
text=ToCharacterCode[text]-97;
Return[text]]
ToNumericForm[ "GHIJKLM "]
We also need the inverse of this operation, to convert a list of numbers modulo
26 to
the string form.
ToTextForm[ plain_List]:=FromCharacterCode[plain+97]