-
-
Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathpolyalphabetic_cipher
55 lines (42 loc) · 1.51 KB
/
polyalphabetic_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
def encrypt(text, key):
#Encrypts the plaintext using the polyalphabetic cipher.
encrypted_text = []
key = key.upper()
key_length = len(key)
key_index = 0
for char in text:
if char.isalpha():
shift = ord(key[key_index]) - ord('A')
if char.isupper():
new_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
else:
new_char = chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
encrypted_text.append(new_char)
key_index = (key_index + 1) % key_length
else:
encrypted_text.append(char)
return ''.join(encrypted_text)
def decrypt(text, key):
#Decrypts the ciphertext using the polyalphabetic cipher
decrypted_text = []
key = key.upper()
key_length = len(key)
key_index = 0
for char in text:
if char.isalpha():
shift = ord(key[key_index]) - ord('A')
if char.isupper():
new_char = chr((ord(char) - ord('A') - shift) % 26 + ord('A'))
else:
new_char = chr((ord(char) - ord('a') - shift) % 26 + ord('a'))
decrypted_text.append(new_char)
key_index = (key_index + 1) % key_length
else:
decrypted_text.append(char)
return ''.join(decrypted_text)
plaintext = "HELLO, WORLD!"
key = "KEY"
ciphertext = encrypt(plaintext, key)
print("Encrypted Text:", ciphertext)
decrypted_text = decrypt(ciphertext, key)
print("Decrypted Text:", decrypted_text)