Build a keyed monoalphabetic substitution: generate the substitution alphabet from a keyword, encrypt, decrypt, and confirm the round trip.
Build a keyed monoalphabetic substitution: generate the substitution alphabet from a keyword, encrypt, decrypt, and confirm the round trip.
Answer
ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def keygen(keyword): key = [] for ch in keyword.upper() + ALPHA: if ch in ALPHA and ch not in key: key.append(ch) return ''.join(key) def encrypt(text, key): table = dict(zip(ALPHA, key)) return ''.join(table.get(ch, ch) for ch in text.upper()) def decrypt(text, key): table = dict(zip(key, ALPHA)) return ''.join(table.get(ch, ch) for ch in text.upper()) K = keygen('HARBOUR') MSG = 'REVERSIBLEORNOTHING' CT = encrypt(MSG, K) print(K) print(CT) print(decrypt(CT, K)) print(decrypt(CT, K) == MSG)
SB5e ch20 §20.1 (principles only — the 5e does not work classical ciphers); worked ciphers, keys and numbers original