-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenère_cipher_algorithm.py
49 lines (41 loc) · 1.66 KB
/
vigenère_cipher_algorithm.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
def _pad_key(plaintext, key):
padded_key = ''
i = 0
for char in plaintext:
if char.isalpha():
padded_key += key[i % len(key)]
i +=1
else:
padded_key += ' '
return padded_key
def _encrypt_decrypt_char(plaintext_char, key_char, mode='encrypt'):
if plaintext_char.isalpha():
first_alphabet_letter = 'a'
if plaintext_char.isupper():
first_alphabet_letter = 'A'
old_char_position = ord(plaintext_char) - ord(first_alphabet_letter)
key_char_position = ord(key_char.lower()) - ord('a')
if mode == 'encrypt':
new_char_position = (old_char_position + key_char_position) % 26
else:
new_char_position = (old_char_position - key_char_position+26) % 26
return chr(new_char_position + ord(first_alphabet_letter))
return plaintext_char
def encrypt(plaintext, key):
ciphertext = ''
padded_key = _pad_key(plaintext, key)
for plaintext_char, key_char in zip(plaintext, padded_key):
ciphertext += _encrypt_decrypt_char(plaintext_char, key_char)
return ciphertext
def decrypt(ciphertext, key):
ciphertext = ''
padded_key = _pad_key(ciphertext, key)
for ciphertext_char, key_char in zip(ciphertext, padded_key):
ciphertext += _encrypt_decrypt_char(ciphertext_char, key_char, mode='decrypt')
return plaintext
plaintext = input('Enter a message: ')
key = input('Enter a key: ')
ciphertext = encrypt(plaintext, key)
decrypted_plaintext = decrypt(ciphertext, key)
print(f'Ciphertext: {ciphertext}')
print(f'Decrypted Plaintext: {decrypted_plaintext}')