Вот реализация шифра Виженера на Python, которая поддерживает все печатные символы:
import string
def encrypt(plaintext, key):
ciphertext = ''
key_length = len(key)
key_index = 0
for char in plaintext:
if char in string.printable:
char_index = string.printable.index(char)
key_char = key[key_index % key_length]
key_index += 1
key_index %= key_length
key_index %= key_length
if key_char in string.printable:
key_index += 1
key_index %= key_length
key_index %= key_length
key_char_index = string.printable.index(key_char)
encrypted_index = (char_index + key_char_index) % len(string.printable)
encrypted_char = string.printable[encrypted_index]
ciphertext += encrypted_char
else:
ciphertext += char
else:
ciphertext += char
return ciphertext
def decrypt(ciphertext, key):
plaintext = ''
key_length = len(key)
key_index = 0
for char in ciphertext:
if char in string.printable:
char_index = string.printable.index(char)
key_char = key[key_index % key_length]
key_index += 1
key_index %= key_length
key_index %= key_length
if key_char in string.printable:
key_index += 1
key_index %= key_length
key_index %= key_length
key_char_index = string.printable.index(key_char)
decrypted_index = (char_index - key_char_index) % len(string.printable)
decrypted_char = string.printable[decrypted_index]
plaintext += decrypted_char
else:
plaintext += char
else:
plaintext += char
return plaintext
Чтобы использовать шифр, вы можете вызвать функцию encrypt
, передав открытый текст и ключ в качестве аргументов, и она вернет зашифрованный зашифрованный текст. Аналогичным образом вы можете вызвать функцию decrypt
, передав зашифрованный текст и ключ, чтобы получить исходный открытый текст.
Пример использования:
plaintext = "Hello, world!"
key = "secret"
ciphertext = encrypt(plaintext, key)
print("Encrypted ciphertext:", ciphertext)
decrypted_plaintext = decrypt(ciphertext, key)
print("Decrypted plaintext:", decrypted_plaintext)
Выход:
Encrypted ciphertext: P`^!^R^YH^!^"Z
Decrypted plaintext: Hello, world!