-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathceasar_shift_cipher.py
56 lines (42 loc) · 1.44 KB
/
ceasar_shift_cipher.py
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
"""
The Ceasar cipher is one of the simplest and one of the earliest known ciphers.
It is a type of substitution cipher that 'shifts' a letter by a fixed amount in the alphabet.
For example with a shift = 3:
a -> d
b -> e
.
.
.
z -> c
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
* 2019-11-07 Initial programming
"""
# This alphabet is of 27 letters since I included a space, but normally it is of 26 letters.
# If you wish to include more letters you need to expand the alphabet used. For example you cannot use '!', '@' now.
alphabet = "abcdefghijklmnopqrstuvwxyz "
letter_to_index = dict(zip(alphabet, range(len(alphabet))))
index_to_letter = dict(zip(range(len(alphabet)), alphabet))
def encrypt(message, shift=3):
cipher = ""
for letter in message:
number = (letter_to_index[letter] + shift) % len(letter_to_index)
letter = index_to_letter[number]
cipher += letter
return cipher
def decrypt(cipher, shift=3):
decrypted = ""
for letter in cipher:
number = (letter_to_index[letter] - shift) % len(letter_to_index)
letter = index_to_letter[number]
decrypted += letter
return decrypted
# def main():
# message = 'attackatnoon'
# cipher = encrypt(message, shift=3)
# decrypted = decrypt(cipher, shift=3)
#
# print('Original message: ' + message)
# print('Encrypted message: ' + cipher)
# print('Decrypted message: ' + decrypted)
#
# main()