I am trying to create functions for encoding and decoding an affine cipher in Mathematica. I have written these two functions:
EncryptChar[char_, a_, b_] :=
Module[{alphabet, position, shift, mod},
alphabet = Alphabet[];
position = Position[alphabet, char][[1]];
position = position[[1]];
shift = Mod[a*position + b, 26];
Return[alphabet[[shift]]];];
DecryptChar[char_, a_, b_] :=
Module[{alphabet, position, shift, mod},
alphabet = Alphabet[];
position = Position[alphabet, char][[1]];
position = position[[1]];
shift = Mod[a^-1*(position - b), 26];
Return [alphabet[[shift]]];];
And when I try to decode char "p", I get this error:
DecryptChar["p", 3, 5]
During evaluation of In[116]:= Part::pkspec1: The expression 11/3 cannot be used as a part specification. >>
{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}[[11/3]]
What have I done wrong?
a^-1
is supposed to be the modular inverse ofa
rather than just1/a
? Yes: replacea^-1
withPowerMod[a, -1, 26]
in the definition ofDecryptChar
. $\endgroup$a
is relatively prime to the number of characters in your allowable alphabet (26 in this case)? $\endgroup$