-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.py
More file actions
70 lines (48 loc) · 1.54 KB
/
caesar_cipher.py
File metadata and controls
70 lines (48 loc) · 1.54 KB
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
62
63
64
65
66
67
68
69
70
import string
from file_utils import remove_accents
ALPHABET = [letter for letter in string.ascii_lowercase]
def encrypt(original_message, key):
'''
Encrypts a message using the caesar cypher
:params original_message, key
:returns encrypted_message
'''
encrypted_message = ''
if type(key) == str:
try:
key = ALPHABET.index(key) + 1
except ValueError:
raise ValueError()
# Encrypts the original message then stores in the return variable
for letter in remove_accents(original_message.lower()):
if letter in ALPHABET:
index = ALPHABET.index(letter)
index += key
if index >= len(ALPHABET):
index -= len(ALPHABET)
encrypted_message += ALPHABET[index]
else:
encrypted_message += letter
return encrypted_message
def decrypt(encrypted_message, key):
'''
Decrypts a message using the caesar cypher
:params encrypted_message, key
:returns translated
'''
translated = ''
if type(key) == str:
try:
key = ALPHABET.index(key) + 1
except ValueError:
raise ValueError()
for letter in remove_accents(encrypted_message.lower()):
if letter in ALPHABET:
index = ALPHABET.index(letter)
index -= key
if index < 0:
index += len(ALPHABET)
translated += ALPHABET[index]
else:
translated += letter
return translated