维吉尼亚密python简单实现
时间: 2023-10-30 15:07:43 浏览: 95
维吉尼亚密码是一种古典密码体制,通过使用一个关键字对明文进行加密。下面是一个简单的Python实现:
```python
def vigenere_encrypt(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
if char.isupper():
char_offset = ord('A')
else:
char_offset = ord('a')
key_shift = ord(key[key_index % len(key)].upper()) - ord('A')
encrypted_char = chr((ord(char) - char_offset + key_shift) % 26 + char_offset)
ciphertext += encrypted_char
key_index += 1
else:
ciphertext += char
return ciphertext
def vigenere_decrypt(ciphertext, key):
plaintext = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
if char.isupper():
char_offset = ord('A')
else:
char_offset = ord('a')
key_shift = ord(key[key_index % len(key)].upper()) - ord('A')
decrypted_char = chr((ord(char) - char_offset - key_shift) % 26 + char_offset)
plaintext += decrypted_char
key_index += 1
else:
plaintext += char
return plaintext
```
使用上述代码,您可以调用`vigenere_encrypt`函数进行加密,调用`vigenere_decrypt`函数进行解密。例如:
```python
plaintext = "Hello, World!"
key = "KEY"
ciphertext = vigenere_encrypt(plaintext, key)
print("密文为:", ciphertext)
decrypted_text = vigenere_decrypt(ciphertext, key)
print("明文为:", decrypted_text)
```
这是一个简单的维吉尼亚密码的Python实现。您可以根据需要对其进行扩展和修改。
阅读全文