fügt mono.py hinzu
parent
def2413f91
commit
3b59fcf9f6
@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
Module to encrypt and decrypt a monoalphabetic cipher.
|
||||
"""
|
||||
|
||||
from string import ascii_lowercase
|
||||
from collections import OrderedDict
|
||||
|
||||
def subs_alphabet(key):
|
||||
return list(OrderedDict.fromkeys(key + ascii_lowercase))
|
||||
|
||||
|
||||
def mono_encrypt(plaintext, key):
|
||||
subs_dict = OrderedDict(zip( ascii_lowercase, subs_alphabet(key) ))
|
||||
enc = ""
|
||||
for char in plaintext.lower():
|
||||
enc += subs_dict[char]
|
||||
return enc
|
||||
|
||||
def mono_decrypt(ciphertext, key):
|
||||
subs_dict = OrderedDict(zip( subs_alphabet(key), ascii_lowercase ))
|
||||
dec = ""
|
||||
for char in ciphertext.lower():
|
||||
dec += subs_dict[char]
|
||||
return dec
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys, os
|
||||
import argparse
|
||||
|
||||
# cannot import from a parent package if called directly
|
||||
# without modifying PYTHONPATH or sys.path
|
||||
file_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
file_parent_dir = os.path.dirname(file_dir)
|
||||
sys.path.append(file_parent_dir)
|
||||
|
||||
from libex01 import read_text
|
||||
|
||||
def parse_args(sys_argv):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("FILE")
|
||||
command_group = parser.add_mutually_exclusive_group(required=True)
|
||||
command_group.add_argument("--encrypt", metavar="KEY")
|
||||
command_group.add_argument("--decrypt", metavar="KEY")
|
||||
parser.add_argument("--out", metavar="FILE")
|
||||
return parser.parse_args(sys_argv[1:])
|
||||
|
||||
def write_output(output, outfile=None):
|
||||
if outfile != None:
|
||||
with open(outfile, 'w') as f:
|
||||
f.write(output)
|
||||
else:
|
||||
print(output)
|
||||
|
||||
args = parse_args(sys.argv)
|
||||
|
||||
txt = read_text(args.FILE)
|
||||
if args.encrypt:
|
||||
enc = mono_encrypt(txt, args.encrypt)
|
||||
write_output(enc, args.out)
|
||||
else:
|
||||
dec = mono_decrypt(txt, args.decrypt)
|
||||
write_output(dec, args.out)
|
||||
Loading…
Reference in New Issue