-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar_cipher
61 lines (42 loc) · 1.69 KB
/
caesar_cipher
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter
with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI"
to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encoded
message can either use frequency analysis to guess the key, or just try all 25 keys.
Time to implement: 1 hour
"""
from langdetect import detect
def cleanup(message):
PUNC = "!?.#@$%^&*()"
message = message.lower()
final = ""
for i in message:
final = final + i.strip(PUNC)
return final
def caesar_cipher(cipher_type, message, encode=True):
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
message = cleanup(message)
start = ALPHABET.find(cipher_type)
ciph_letters = ALPHABET[start:] + ALPHABET[:start]
translated = ""
if encode == True:
output, input = ciph_letters, ALPHABET
else:
output, input = ALPHABET, ciph_letters
for letter in message:
if letter == " ":
translated = translated + letter
else:
translated = translated + output[input.find(letter)]
return translated
x = caesar_cipher("g", "Procrastination is awesome!")
print(x)
def decipher(message):
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
for letter in ALPHABET:
translated = caesar_cipher(letter, message, encode=False)
if detect(translated) == "en":
return translated, letter
return "Cannot be translated to English"
print(decipher(x))