-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar_cipher.py
101 lines (62 loc) · 2.3 KB
/
caesar_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# Program to encrypt passwords, words, with an offset
key_letter = 'abcdefghijklmnopqrstuvwxyz'
def encrypt(letter: str, shift: int):
new_index = key_letter.index(letter) + shift
return key_letter[new_index]
print(encrypt("b", 3)) # result is e, shift by 3
def encrypt_word(word, shift):
encrypted_word = ''
for letter in word:
new_index = key_letter.index(letter) + shift
encrypted_word += key_letter[new_index]
return encrypted_word
print(encrypt_word('mon', 4))
# Using alphabet import and protection against moving beyond the range of the alphabet i.e. return to start a, b, c ..
import string
key_lett = string.ascii_letters # or lowercase
def encrypt(word, shift):
encrypted_word = ''
for letter in word:
new_index = key_lett.index(letter) + shift
encrypted_word += key_lett[new_index]
return encrypted_word
word = input("Enter word to encrypt: ")
shift = int(input("Enter what the offset should be: "))
print(encrypt(word, shift))
# With dictionary use
import string
alphabet = string.ascii_letters
def encrypt(word, shift):
key_val = {}
for letter in word:
new_index = (alphabet.index(letter) + shift) % len(alphabet)
key_val[letter] = alphabet[new_index]
return key_val
encrypted = encrypt('something', 3)
print(encrypted)
# encryption and decryption
import string
alphab = string.ascii_letters
def encrpytion(word, shift):
key_v = {}
for letter in word:
new_index = (alphab.index(letter) + shift) % len(alphab)
key_v[letter] = alphab[new_index]
encrypted_word = ''
for letter in word:
encrypted_word += key_v[letter]
return encrypted_word
def decryption(word, shift):
key = {}
for letter in alphab:
new_index = (alphab.index(letter) + shift) % len(alphab)
key[alphab[new_index]] = letter
encrypted_word = ''
for letter in word:
encrypted_word += key[letter]
return encrypted_word
before_encryption = input('Enter the word: ')
print(f'The word before encryption: {before_encryption}')
encrypted = encrpytion(before_encryption, 3)
print(f'After encryption: {encrypted}')
print(f'After decryption: {decryption(encrypted, 3)}')