维吉尼亚加密解密Python
时间: 2023-11-29 17:46:14 浏览: 89
以下是Python实现维吉尼亚加密/解密的代码示例:
```python
# 加密函数
def encrypt_vigenere(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
# 将字母转换为0-25的数字
char_num = ord(char.lower()) - 97
key_num = ord(key[key_index].lower()) - 97
# 加密运算
new_num = (char_num + key_num) % 26
# 将数字转换为字母
new_char = chr(new_num + 97)
ciphertext += new_char
# 更新密钥索引
key_index = (key_index + 1) % len(key)
else:
ciphertext += char
return ciphertext
# 解密函数
def decrypt_vigenere(ciphertext, key):
plaintext = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
# 将字母转换为0-25的数字
char_num = ord(char.lower()) - 97
key_num = ord(key[key_index].lower()) - 97
# 解密运算
new_num = (char_num - key_num) % 26
# 将数字转换为字母
new_char = chr(new_num + 97)
plaintext += new_char
# 更新密钥索引
key_index = (key_index + 1) % len(key)
else:
plaintext += char
return plaintext
```
使用示例:
```python
plaintext = "HELLO WORLD"
key = "SECRET"
ciphertext = encrypt_vigenere(plaintext, key)
print(ciphertext) # 输出:"DSCWR XHWAH"
decrypted_plaintext = decrypt_vigenere(ciphertext, key)
print(decrypted_plaintext) # 输出:"HELLO WORLD"
```
阅读全文