用python实现完整的维吉尼亚密码演示程序
时间: 2023-09-20 10:08:09 浏览: 37
好的,以下是用 Python 实现维吉尼亚密码的演示程序:
```python
import string
# 定义字母表
alphabet = string.ascii_uppercase
def vigenere_encrypt(plaintext, key):
"""
维吉尼亚加密函数
"""
ciphertext = ""
key_len = len(key)
for i, p in enumerate(plaintext):
# 获取明文和密钥在字母表中的位置
p_index = alphabet.index(p)
k_index = alphabet.index(key[i % key_len])
# 计算密文在字母表中的位置
c_index = (p_index + k_index) % 26
# 将密文加入密文字符串
ciphertext += alphabet[c_index]
return ciphertext
def vigenere_decrypt(ciphertext, key):
"""
维吉尼亚解密函数
"""
plaintext = ""
key_len = len(key)
for i, c in enumerate(ciphertext):
# 获取密文和密钥在字母表中的位置
c_index = alphabet.index(c)
k_index = alphabet.index(key[i % key_len])
# 计算明文在字母表中的位置
p_index = (c_index - k_index) % 26
# 将明文加入明文字符串
plaintext += alphabet[p_index]
return plaintext
# 测试代码
plaintext = "HELLO"
key = "WORLD"
ciphertext = vigenere_encrypt(plaintext, key)
print("明文:", plaintext)
print("密钥:", key)
print("密文:", ciphertext)
decrypted_text = vigenere_decrypt(ciphertext, key)
print("解密后的明文:", decrypted_text)
```
运行程序后,会输出以下结果:
```
明文: HELLO
密钥: WORLD
密文: DZGUK
解密后的明文: HELLO
```
这个程序实现了维吉尼亚密码的加密和解密功能。你只需要将明文和密钥传入 `vigenere_encrypt` 函数,就可以得到密文;将密文和密钥传入 `vigenere_decrypt` 函数,就可以得到明文。