|
| 1 | +""" |
| 2 | +caesar cipher algorithm, implement in python |
| 3 | +complexity: O(n) |
| 4 | +""" |
| 5 | + |
| 6 | +from string import ascii_letters |
| 7 | + |
| 8 | + |
| 9 | +def encrypt(input_string: str, key: int) -> str: |
| 10 | + alpha = ascii_letters |
| 11 | + result = "" |
| 12 | + for letter in input_string: |
| 13 | + if letter not in alpha: |
| 14 | + result += letter |
| 15 | + continue |
| 16 | + new_key = (alpha.index(letter) + key) % len(alpha) |
| 17 | + result += alpha[new_key] |
| 18 | + return result |
| 19 | + |
| 20 | + |
| 21 | +def decrypt(input_string: str, key: int) -> str: |
| 22 | + key *= -1 |
| 23 | + return encrypt(input_string, key) |
| 24 | + |
| 25 | + |
| 26 | +def brute_force(input_string: str) -> dict: |
| 27 | + alpha = ascii_letters |
| 28 | + key = 1 |
| 29 | + brute_force_data = {} |
| 30 | + while key <= len(alpha): |
| 31 | + result = decrypt(input_string, key) |
| 32 | + brute_force_data[key] = result |
| 33 | + key += 1 |
| 34 | + return brute_force_data |
| 35 | + |
| 36 | + |
| 37 | +if __name__ == '__main__': |
| 38 | + # encrypt & decrypt mohammad dori |
| 39 | + print(encrypt('mohammad dori', 8)) |
| 40 | + print(decrypt('uwpiuuil lwzq', 8)) |
| 41 | + # encrypt & decrypt dori-dev |
| 42 | + print(encrypt('dori-dev', 8)) |
| 43 | + print(decrypt('lwzq-lmD', 8)) |
| 44 | + # return brute force data for lwzq-lmD encrypted text |
| 45 | + # and find the key `8` and true text `dori-dev` |
| 46 | + print(brute_force('lwzq-lmD')) |
0 commit comments