forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvernam_cipher.py
42 lines (36 loc) · 1.05 KB
/
vernam_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
defvernam_encrypt(plaintext: str, key: str) ->str:
"""
>>> vernam_encrypt("HELLO","KEY")
'RIJVS'
"""
ciphertext=""
foriinrange(len(plaintext)):
ct=ord(key[i%len(key)]) -65+ord(plaintext[i]) -65
whilect>25:
ct=ct-26
ciphertext+=chr(65+ct)
returnciphertext
defvernam_decrypt(ciphertext: str, key: str) ->str:
"""
>>> vernam_decrypt("RIJVS","KEY")
'HELLO'
"""
decrypted_text=""
foriinrange(len(ciphertext)):
ct=ord(ciphertext[i]) -ord(key[i%len(key)])
whilect<0:
ct=26+ct
decrypted_text+=chr(65+ct)
returndecrypted_text
if__name__=="__main__":
fromdoctestimporttestmod
testmod()
# Example usage
plaintext="HELLO"
key="KEY"
encrypted_text=vernam_encrypt(plaintext, key)
decrypted_text=vernam_decrypt(encrypted_text, key)
print("\n\n")
print("Plaintext:", plaintext)
print("Encrypted:", encrypted_text)
print("Decrypted:", decrypted_text)