forked from asweigart/the-big-book-of-small-python-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvigenerecipher.py
110 lines (86 loc) · 3.73 KB
/
vigenerecipher.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
102
103
104
105
106
107
108
109
110
"""Vigenère Cipher, by Al Sweigart [email protected]
The Vigenère cipher is a polyalphabetic substitution cipher that was
powerful enough to remain unbroken for centuries.
More info at: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: short, cryptography, math"""
try:
import pyperclip # pyperclip copies text to the clipboard.
except ImportError:
pass # If pyperclip is not installed, do nothing. It's no big deal.
# Every possible symbol that can be encrypted/decrypted:
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
print('''Vigenère Cipher, by Al Sweigart [email protected]
The Viegenère cipher is a polyalphabetic substitution cipher that was
powerful enough to remain unbroken for centuries.''')
# Let the user specify if they are encrypting or decrypting:
while True: # Keep asking until the user enters e or d.
print('Do you want to (e)ncrypt or (d)ecrypt?')
response = input('> ').lower()
if response.startswith('e'):
myMode = 'encrypt'
break
elif response.startswith('d'):
myMode = 'decrypt'
break
print('Please enter the letter e or d.')
# Let the user specify the key to use:
while True: # Keep asking until the user enters a valid key.
print('Please specify the key to use.')
print('It can be a word or any combination of letters:')
response = input('> ').upper()
if response.isalpha():
myKey = response
break
# Let the user specify the message to encrypt/decrypt:
print('Enter the message to {}.'.format(myMode))
myMessage = input('> ')
# Perform the encryption/decryption:
if myMode == 'encrypt':
translated = encryptMessage(myMessage, myKey)
elif myMode == 'decrypt':
translated = decryptMessage(myMessage, myKey)
print('%sed message:' % (myMode.title()))
print(translated)
try:
pyperclip.copy(translated)
print('Full %sed text copied to clipboard.' % (myMode))
except:
pass # Do nothing if pyperclip wasn't installed.
def encryptMessage(message, key):
"""Encrypt the message using the key."""
return translateMessage(message, key, 'encrypt')
def decryptMessage(message, key):
"""Decrypt the message using the key."""
return translateMessage(message, key, 'decrypt')
def translateMessage(message, key, mode):
"""Encrypt or decrypt the message using the key."""
translated = [] # Stores the encrypted/decrypted message string.
keyIndex = 0
key = key.upper()
for symbol in message: # Loop through each character in message.
num = LETTERS.find(symbol.upper())
if num != -1: # -1 means symbol.upper() was not in LETTERS.
if mode == 'encrypt':
# Add if encrypting:
num += LETTERS.find(key[keyIndex])
elif mode == 'decrypt':
# Subtract if decrypting:
num -= LETTERS.find(key[keyIndex])
num %= len(LETTERS) # Handle the potential wrap-around.
# Add the encrypted/decrypted symbol to translated.
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1 # Move to the next letter in the key.
if keyIndex == len(key):
keyIndex = 0
else:
# Just add the symbol without encrypting/decrypting:
translated.append(symbol)
return ''.join(translated)
# If this program was run (instead of imported), run the program:
if __name__ == '__main__':
main()