File tree 1 file changed +55
-0
lines changed
1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ def encrypt(text, key):
2
+
3
+ #Encrypts the plaintext using the polyalphabetic cipher.
4
+
5
+ encrypted_text = []
6
+ key = key.upper()
7
+ key_length = len(key)
8
+ key_index = 0
9
+
10
+ for char in text:
11
+ if char.isalpha():
12
+ shift = ord(key[key_index]) - ord('A')
13
+ if char.isupper():
14
+ new_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
15
+ else:
16
+ new_char = chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
17
+ encrypted_text.append(new_char)
18
+ key_index = (key_index + 1) % key_length
19
+ else:
20
+ encrypted_text.append(char)
21
+
22
+ return ''.join(encrypted_text)
23
+
24
+
25
+ def decrypt(text, key):
26
+ #Decrypts the ciphertext using the polyalphabetic cipher
27
+
28
+ decrypted_text = []
29
+ key = key.upper()
30
+ key_length = len(key)
31
+ key_index = 0
32
+
33
+ for char in text:
34
+ if char.isalpha():
35
+ shift = ord(key[key_index]) - ord('A')
36
+ if char.isupper():
37
+ new_char = chr((ord(char) - ord('A') - shift) % 26 + ord('A'))
38
+ else:
39
+ new_char = chr((ord(char) - ord('a') - shift) % 26 + ord('a'))
40
+ decrypted_text.append(new_char)
41
+ key_index = (key_index + 1) % key_length
42
+ else:
43
+ decrypted_text.append(char)
44
+
45
+ return ''.join(decrypted_text)
46
+
47
+
48
+ plaintext = "HELLO, WORLD!"
49
+ key = "KEY"
50
+
51
+ ciphertext = encrypt(plaintext, key)
52
+ print("Encrypted Text:", ciphertext)
53
+
54
+ decrypted_text = decrypt(ciphertext, key)
55
+ print("Decrypted Text:", decrypted_text)
You can’t perform that action at this time.
0 commit comments