维吉尼亚密码加解密python实现
时间: 2023-07-30 15:07:23 浏览: 63
以下是使用Python实现维吉尼亚密码加解密的完整示例代码:
```
def encrypt_vigenere(plaintext, keyword):
"""
使用维吉尼亚密码加密明文。
"""
ciphertext = ""
keyword = keyword.upper()
keyword_len = len(keyword)
for i in range(len(plaintext)):
char = plaintext[i]
if char.isalpha():
keyword_index = i % keyword_len
keyword_char = keyword[keyword_index]
shift = ord(keyword_char) - 65
if char.isupper():
ciphertext += chr((ord(char) + shift - 65) % 26 + 65)
else:
ciphertext += chr((ord(char) + shift - 97) % 26 + 97)
else:
ciphertext += char
return ciphertext
def decrypt_vigenere(ciphertext, keyword):
"""
使用维吉尼亚密码解密密文。
"""
plaintext = ""
keyword = keyword.upper()
keyword_len = len(keyword)
for i in range(len(ciphertext)):
char = ciphertext[i]
if char.isalpha():
keyword_index = i % keyword_len
keyword_char = keyword[keyword_index]
shift = ord(keyword_char) - 65
if char.isupper():
plaintext += chr((ord(char) - shift - 65) % 26 + 65)
else:
plaintext += chr((ord(char) - shift - 97) % 26 + 97)
else:
plaintext += char
return plaintext
```
该代码包含两个函数:`encrypt_vigenere()`用于加密明文,`decrypt_vigenere()`用于解密密文。两个函数都接受两个参数:明文或密文(plaintext或ciphertext)和关键字(keyword)。
示例用法:
```
plaintext = "HELLO WORLD"
keyword = "SECRET"
ciphertext = encrypt_vigenere(plaintext, keyword)
print(ciphertext) # 输出:"DPLLR XPLRH"
decrypted_plaintext = decrypt_vigenere(ciphertext, keyword)
print(decrypted_plaintext) # 输出:"HELLO WORLD"
```
注意:在使用维吉尼亚密码进行加密时,关键字应该是不易猜测的,否则加密的安全性会受到影响。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)