|
| 1 | +""" |
| 2 | +Author: Mohit Radadiya |
| 3 | +""" |
| 4 | + |
| 5 | +from string import ascii_uppercase |
| 6 | + |
| 7 | +dict1 = {char: i for i, char in enumerate(ascii_uppercase)} |
| 8 | +dict2 = {i: char for i, char in enumerate(ascii_uppercase)} |
| 9 | + |
| 10 | + |
| 11 | +# This function generates the key in |
| 12 | +# a cyclic manner until it's length isn't |
| 13 | +# equal to the length of original text |
| 14 | +def generate_key(message: str, key: str) -> str: |
| 15 | + """ |
| 16 | + >>> generate_key("THE GERMAN ATTACK","SECRET") |
| 17 | + 'SECRETSECRETSECRE' |
| 18 | + """ |
| 19 | + x = len(message) |
| 20 | + i = 0 |
| 21 | + while True: |
| 22 | + if x == i: |
| 23 | + i = 0 |
| 24 | + if len(key) == len(message): |
| 25 | + break |
| 26 | + key += key[i] |
| 27 | + i += 1 |
| 28 | + return key |
| 29 | + |
| 30 | + |
| 31 | +# This function returns the encrypted text |
| 32 | +# generated with the help of the key |
| 33 | +def cipher_text(message: str, key_new: str) -> str: |
| 34 | + """ |
| 35 | + >>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE") |
| 36 | + 'BDC PAYUWL JPAIYI' |
| 37 | + """ |
| 38 | + cipher_text = "" |
| 39 | + i = 0 |
| 40 | + for letter in message: |
| 41 | + if letter == " ": |
| 42 | + cipher_text += " " |
| 43 | + else: |
| 44 | + x = (dict1[letter] - dict1[key_new[i]]) % 26 |
| 45 | + i += 1 |
| 46 | + cipher_text += dict2[x] |
| 47 | + return cipher_text |
| 48 | + |
| 49 | + |
| 50 | +# This function decrypts the encrypted text |
| 51 | +# and returns the original text |
| 52 | +def original_text(cipher_text: str, key_new: str) -> str: |
| 53 | + """ |
| 54 | + >>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE") |
| 55 | + 'THE GERMAN ATTACK' |
| 56 | + """ |
| 57 | + or_txt = "" |
| 58 | + i = 0 |
| 59 | + for letter in cipher_text: |
| 60 | + if letter == " ": |
| 61 | + or_txt += " " |
| 62 | + else: |
| 63 | + x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 |
| 64 | + i += 1 |
| 65 | + or_txt += dict2[x] |
| 66 | + return or_txt |
| 67 | + |
| 68 | + |
| 69 | +def main(): |
| 70 | + message = "THE GERMAN ATTACK" |
| 71 | + key = "SECRET" |
| 72 | + key_new = generate_key(message, key) |
| 73 | + s = cipher_text(message, key_new) |
| 74 | + print(f"Encrypted Text = {s}") |
| 75 | + print(f"Original Text = {original_text(s, key_new)}") |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == "__main__": |
| 79 | + import doctest |
| 80 | + |
| 81 | + doctest.testmod() |
| 82 | + main() |
0 commit comments