Haskell:
Code:
import Data.Char
import System(getArgs)
data Crypt = Encrypt | Decrypt deriving (Eq)
-- Takes two characters, one from the original string
-- and one from the corresponding index of the key string.
-- Returns the encrypted (or decrypted) character.
vigenere :: Crypt -> Char -> Char -> Char
vigenere e old key = chr $ 65 + ((p_i `f` k_i) `mod` 26)
where p_i = (ord old) - 65
k_i = (ord key) - 65
f = if e == Encrypt then (+) else (-)
-- Expects 3 command line arguments, the password, the key
-- and an 'e' or 'd' if you want to encrypt or decrypt
-- respectively. The password will be cycled as necessary
-- to be the same length as the source text
main = do
args <- getArgs
let [source, pass, x] = take 3 args
password = take (length source) (cycle pass)
e = case (head x) of
'e' -> Encrypt
'd' -> Decrypt
in putStrLn $ zipWith (vigenere e) source password
Here's a similar approach in Python, whited out for the time being:
Code:
import sys
import operator
from itertools import cycle, islice
def vigenere(f, old, key):
p_i = ord(old) - 65
k_i = ord(key) - 65
return chr(65 + (f(p_i, k_i) % 26))
def main():
[source, passw, x] = sys.argv[1:4]
password = list(islice(cycle(passw), 0, len(source)))
if x == "e":
f = operator.add
elif x == "d":
f = operator.sub
s = ""
for i in xrange(len(source)):
s += vigenere(f, source[i], password[i])
print s
main()
Bookmarks