-
Notifications
You must be signed in to change notification settings - Fork 1k
/
vigenere_cipher.py
67 lines (51 loc) · 1.47 KB
/
vigenere_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
# Vigenere Cipher python code.
def encrypt(msg, key):
cipher = ""
n = len(key)
i = 0
for l in msg:
# finding the index of the character
p = int(ord(l) + ord(key[i % n])) % 26
# to perform the shift with the key
cipher += chr(p + ord('A'))
i += 1
return cipher
def decrypt(cipher, key):
msg = ""
n = len(key)
j = 0
for l in cipher:
p = int(ord(l) - ord(key[j % n]) + 26) % 26
msg += chr(p + ord('A'))
j += 1
return msg
if __name__=='__main__':
# Use uppercase only
choice = int(input("Choose 1 if you want to ENCRYPT or 2 if you want to DECRYPT: "))
if(choice == 1):
msg = input("Enter a plaintext message: ")
key = input("Enter a keyword: ")
# encrypting the message
cipher = encrypt(msg, key)
print("\nEncrypted message: ", cipher)
elif(choice == 2):
cipher = input("Enter a ciphertext: ")
key = input("Enter a keyword: ")
# decrypting the ciphar text
original = decrypt(cipher, key)
print("\nDecrypted message: ", original)
else:
print("\nInvalid choice.")
'''
Sample I/O:
1)
Choose 1 if you want to ENCRYPT or 2 if you want to DECRYPT: 1
Enter a plaintext message: NEOALGO
Enter a keyword: MARS
Encrypted message: ZEFSXGF
2)
Choose 1 if you want to ENCRYPT or 2 if you want to DECRYPT: 2
Enter a ciphertext: ZEFSXGF
Enter a keyword: MARS
Decrypted message: NEOALGO
'''