From 3b59fcf9f63abcf62c53c84d14d15c486ae7618d Mon Sep 17 00:00:00 2001 From: Daniel Tschertkow Date: Mon, 23 Nov 2020 01:12:31 +0100 Subject: [PATCH] =?UTF-8?q?f=C3=BCgt=20mono.py=20hinzu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mono/mono.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100755 src/mono/mono.py diff --git a/src/mono/mono.py b/src/mono/mono.py new file mode 100755 index 0000000..c63bf75 --- /dev/null +++ b/src/mono/mono.py @@ -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)