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


 
 
{def small_ascii {S.map fromCharCode {S.serie 33 122}}} 
-> small_ascii 
 
{S.length {small_ascii}} = 90
 
{def substitution
 
 {def substitution.r
  {lambda {:w :n :s :i}
   {if {> :i :n}
    then 
    else {let { {:s :s} {:c {W.char2code {A.get :i :w}}}
              } {if {and {>= :c 33} {<= :c 122}}
                 then {W.code2char {+ 33 {% {+ :c {- :s 33}} 90}}} 
                 else {if {= :c 248} then :c else}} 
         }{substitution.r :w :n :s {+ :i 1}} }}}
 
 {lambda {:s :w}
  {let { {:s :s} {:w {S.replace \s by ` in :w}}
       } {S.replace ` 
                 by space 
                 in {substitution.r {A.split :w}
                                    {- {W.length :w} 1}
                                    :s 
                                    0}} }}}
-> substitution
 
1) intitial text:
 
{def txt 
Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase 
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against 
Pharnaces II of Pontus at the Battle of Zela.
} -> txt
 
2) choose the shift:
 
{def shift 13}
-> shift // valid in [0...90] except 5 10 15 29 30 50 53 70 74
 
3) encoding the text
 
 {substitution {shift} {txt}} 
-> cr!v9mcvqv9mcvpvmv&mnmYn'v!m#u%n&rm#"#(yn%y,mn''%vo('rqm'"mW(yv(&mPnr&n%m*u"9mnpp"%qv!tm'"mN##vn!9m(&rqm'urm#u%n&rmv!mnmyr''r%m'"m'urm_"zn!m r!n'rmn%"
(!qmADmOPmns'r%murmunqmnpuvr)rqmnm$(vpxm)vp'"%,mv!muv&m&u"%'m*n%mntnv!&'m]un%!npr&mVVm"sm]"!'(&mn'm'urmOn''yrm"smgryn;
 
4) decoding the text
 
 {substitution {- 90 {shift}} {substitution {shift} {txt}}} 
-> Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase 
in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against 
Pharnaces II of Pontus at the Battle of Zela.
 
