Message Encyption and Decryption

You are given an encoded message and it's real interpretation. Given this encoding you have to find the key that allows you to decode the message. An element in the key is the number of iterations you have to move through the alphabet in order to get from the real character to the decrpyed character. For example, to go from T to B we need 8 iterations.

Your job is to find the key, and then use the key to decrypt a new encoded message if the encoded message to larger than the key, then we wrap back around in the key array.

import string


alpha = string.ascii_lowercase

int_alpha = {i:c for i, c in enumerate(alpha)}
alpha_int = {c:i for i, c in enumerate(alpha)}

def get_key(encode, real):
    code = 0
    key = []

    for i in range(0, len(real)):
        target = encode[i].lower()
        start = real[i].lower()
        if not target.isalpha():
            continue

        while True:
            if target == start:
                key.append(code)
                code = 0
                break

            else:
                cur_alpha_int = alpha_int[start]
                next_alpha = int_alpha[(cur_alpha_int + 1) % 26]
                start = next_alpha
                code += 1

    return key


def increment_char(c, by):
    cur_c = c.lower()
    for i in range(0, by):
        cur_alpha_int = alpha_int[cur_c]
        next_alpha = int_alpha[(cur_alpha_int - 1) % 26]
        cur_c = next_alpha

    if c.isupper():
        return cur_c.upper()
    else:
        return cur_c

def decrypt(encrypted_message, key):
    decrpyed = []
    key_iter = 0
    for c in encrypted_message:
        if not c.isalpha():
            decrpyed.append(c)
        else:
            by = key[key_iter % len(key)]
            decryp_c = increment_char(c, by)
            decrpyed.append(decryp_c)
            key_iter += 1

    return ''.join(decrpyed)

key = get_key(encode = "Bjj rwkc", real = "The quic")
print(decrypt("Bjj rwkcs dwpyp fwz ovors wxjs vje tcez fqg", key))  # "The quick brown fox jumps over the lazy dog"

Last updated