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


alphabet = "abcdefghijklmnopqrstuvwxyz".split("")
cipher = alphabet[0:]
cipher.shuffle
encode = {}
decode = {}
for i in alphabet.indexes
    encode[alphabet[i]] = cipher[i]
    decode[cipher[i]] = alphabet[i]
    encode[alphabet[i].upper] = cipher[i].upper
    decode[cipher[i].upper] = alphabet[i].upper
end for
 
apply = function(map, s)
    chars = s.split("")
    for i in chars.indexes
        if map.hasIndex(chars[i]) then chars[i] = map[chars[i]]
    end for
    return chars.join("")
end function
 
msg = "Now is the time for all good men (and women) to come together."
secretCode = apply(encode, msg)
print secretCode
print apply(decode, secretCode)