Substitution Cipher Implementation - File Encryption/Decryption



Task

Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.

This type of Encryption/Decryption scheme is often called a Substitution Cipher.



Related tasks

 Caesar cipher
 Rot-13
 Vigenère Cipher/Cryptanalysis


See also

 Wikipedia: Substitution cipher


main =>
  S = "The quick brown fox jumped over the lazy dog",
  cypher(S,E),  % encrypt
  println(E),
 
  cypher(D, E), % decrypt
  println(D),
 
  S == D,
  println(ok).
 
cypher(O, S) :-
  nonvar(O),
  var(S),
  sub_chars(O,S).
cypher(O, S) :-
  nonvar(S),
  var(O),
  sub_chars(O,S).
 
base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").
subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN").
 
sub_chars(Original,Subbed) :-
  base(Base),
  subs(Subs),
  maplist($sub_char(Base,Subs),Original,Subbed).
 
sub_char([Co|_],[Cs|_],Co,Cs) :- !.
sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs).
 
maplist(Goal, List1, List2) :-
    maplist_(List1, List2, Goal).
 
maplist_([], X, _) :- X = []. 
maplist_([Elem1|Tail1],
         [Elem2|Tail2],
         Goal) :-
    call(Goal, Elem1, Elem2),
    maplist_(Tail1, Tail2, Goal).