python实现Vigenere密码加解密
时间: 2023-11-19 09:04:31 浏览: 107
Vigenere密码是一种多项式替换密码,它使用多个不同的凯撒密码来加密消息。下面是Python实现Vigenere密码加解密的示例代码:
```python
def vigenere_encrypt(plaintext, key):
# 将明文和密钥转换为大写字母
plaintext = plaintext.upper()
key = key.upper()
ciphertext = ""
# 对明文中的每个字母进行加密
for i in range(len(plaintext)):
# 计算密钥中的字母索引,循环使用密钥
key_index = i % len(key)
# 计算明文中的字母索引
plaintext_index = ord(plaintext[i]) - ord('A')
# 计算密钥中的字母索引
key_letter = ord(key[key_index]) - ord('A')
# 计算加密后的字母索引
ciphertext_index = (plaintext_index + key_letter) % 26
# 将加密后的字母添加到密文中
ciphertext += chr(ciphertext_index + ord('A'))
return ciphertext
def vigenere_decrypt(ciphertext, key):
# 将密文和密钥转换为大写字母
ciphertext = ciphertext.upper()
key = key.upper()
plaintext = ""
# 对密文中的每个字母进行解密
for i in range(len(ciphertext)):
# 计算密钥中的字母索引,循环使用密钥
key_index = i % len(key)
# 计算密文中的字母索引
ciphertext_index = ord(ciphertext[i]) - ord('A')
# 计算密钥中的字母索引
key_letter = ord(key[key_index]) - ord('A')
# 计算解密后的字母索引
plaintext_index = (ciphertext_index - key_letter) % 26
# 将解密后的字母添加到明文中
plaintext += chr(plaintext_index + ord('A'))
return plaintext
```
使用示例:
```python
plaintext = "HELLO WORLD"
key = "SECRET"
ciphertext = vigenere_encrypt(plaintext, key)
print("密文:", ciphertext)
decrypted_plaintext = vigenere_decrypt(ciphertext, key)
print("解密后的明文:", decrypted_plaintext)
```
输出结果:
```
密文: TWWQX AZBOA
解密后的明文: HELLO WORLD
```
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)