Hello everyone, after the invitation I received from a friend, to try to program the playfair cipher in mathematica, I started looking for information about it because the one that he provided was not enough. My first place to look was wikipedia, there I found more detailed information and even an example. Later I realized that in Spanish we have 27 letters and the algorithm asks to use a matrix of 5 X 5 for which two letters of the Spanish alphabet should be erased, thanks to the fact that in wikipedia they mention Frequency analysis for Spanish, I could reach the conclusion that the letters I could do without are the letters w and k, leaving me the 25 necessary letters.
Below I share my attempt to playfair cipher.
Text that you want to encrypt, not have blank spaces.
txtclaro = "introduccionalacriptografia";
Building of the matrix.
matrix = Partition[DeleteDuplicates[ Join[Characters[password], Delete[Insert[CharacterRange["a", "z"], "ñ", 15], {{11}, {24}}]]], 5];
MatrixForm[matrix]
Checking that the length of the txtclaro multiply of 2 if not, add an "X" at the end.
If[Mod[StringLength[txtclaro], 2] != 0,
txtclaro = StringInsert[txtclaro, "x", -1]]; letras =
Partition[Characters[txtclaro], 2]; txtclaro =
StringJoin[If[#[[1]] == #[[2]], Insert[#, "x", 2], #] & /@ letras]; If[
Mod[StringLength[txtclaro], 2] != 0,
txtclaro = StringInsert[txtclaro, "x", -1]];
Let's see what happened to txtclaro
txtclaro
Function that applies the rules of system playfair.
newpos[ubica_] :=
Module[{pref = Flatten[ubica, 1]},
Which[#[[1]] != #2[[1]] && #[[2]] != #2[[2]] & @@
pref, {{First[Flatten[pref]], Flatten[pref][[4]]}, {Flatten[pref][[3]],
Flatten[pref][[2]]}}, #[[1]] == #2[[1]] && #[[2]] != #2[[2]] & @@
pref, {{First[Flatten[pref]],
Mod[Flatten[pref][[2]] + 1, 5]}, {First[Flatten[pref]],
Mod[Flatten[pref][[4]] + 1,
5]}}, #[[1]] != #2[[1]] && #[[2]] == #2[[2]] & @@
pref, {{Mod[First[Flatten[pref]] + 1, 5],
Flatten[pref][[2]]}, {Mod[Flatten[pref][[3]] + 1, 5],
Flatten[pref][[2]]}}]]
Operation example, used to encriypt txtclaro shown above.
hur = Partition[Characters[txtclaro], 2]; pos =
Map[Position[matrix, #] &,
hur, {2}]; tomar = (newpos[#] & /@ pos) /. {0 -> 5}; StringJoin[
Extract[matrix, #] & /@ tomar]
I am very sure that this can be improved, reason why which I thank you for your comments and suggestions, since they are of great value for my learning of MATHEMATICA. Thanks in advance.