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


constant plain = tagset('Z','A')&tagset('z','a'),
         key = shuffle(plain)

function encode(string s, integer decrypt=false)
    sequence {p,k} = iff(decrypt?{plain,key}:{key,plain})
    for i=1 to length(s) do
        integer ki = find(s[i],p)
        if ki then s[i] = k[ki] end if
    end for
    return s
end function
 
string original = "A simple example.",
       encoded = encode(original),
       decoded = encode(encoded, true)

printf(1,"original: %s\nencoded: %s\ndecoded: %s\n",{original,encoded,decoded})
