编程实现维吉尼亚密码
时间: 2023-08-13 20:16:13 浏览: 44
好的,维吉尼亚密码是一种基于多表密码的加密方法,它采用了多个不同的凯撒密码。
下面是一个简单的 Python 实现:
```python
def vigenere_cipher(text, key, mode):
# 先将文本和密钥转换为大写字母
text = text.upper()
key = key.upper()
# 生成密钥序列
while len(key) < len(text):
key += key
key = key[:len(text)]
# 生成字母表序列
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# 根据加密或解密模式进行操作
result = ""
for i in range(len(text)):
if text[i] not in alphabet:
result += text[i]
continue
if mode == "encrypt":
# 获取明文字母和密钥字母的位置
text_pos = alphabet.index(text[i])
key_pos = alphabet.index(key[i])
# 计算密文字母的位置
cipher_pos = (text_pos + key_pos) % 26
# 将密文字母加入结果
result += alphabet[cipher_pos]
elif mode == "decrypt":
# 获取密文字母和密钥字母的位置
cipher_pos = alphabet.index(text[i])
key_pos = alphabet.index(key[i])
# 计算明文字母的位置
text_pos = (cipher_pos - key_pos + 26) % 26
# 将明文字母加入结果
result += alphabet[text_pos]
return result
```
这个函数接受三个参数:明文(或密文)、密钥和模式(加密或解密),并返回加密后的密文或解密后的明文。
例如,要加密明文 "HELLO",密钥为 "WORLD":
```python
text = "HELLO"
key = "WORLD"
cipher = vigenere_cipher(text, key, "encrypt")
print(cipher) # 输出:DSCWR
```
要解密密文 "DSCWR",密钥仍为 "WORLD":
```python
cipher = "DSCWR"
text = vigenere_cipher(cipher, key, "decrypt")
print(text) # 输出:HELLO
```