维多利亚加密算法python
时间: 2023-10-29 19:57:15 浏览: 169
以下是使用Python实现维吉尼亚加密算法的代码示例:
```python
def encrypt_vigenere(plain_text, key):
cipher_text = ""
key_len = len(key)
for i in range(len(plain_text)):
char = plain_text[i]
if char.isalpha():
key_char = key[i % key_len].lower()
shift = ord(key_char) - ord('a')
cipher_char = chr((ord(char.lower()) + shift - 97) % 26 + 97)
cipher_text += cipher_char.upper() if char.isupper() else cipher_char
else:
cipher_text += char
return cipher_text
def decrypt_vigenere(cipher_text, key):
plain_text = ""
key_len = len(key)
for i in range(len(cipher_text)):
char = cipher_text[i]
if char.isalpha():
key_char = key[i % key_len].lower()
shift = ord(key_char) - ord('a')
plain_char = chr((ord(char.lower()) - shift - 97) % 26 + 97)
plain_text += plain_char.upper() if char.isupper() else plain_char
else:
plain_text += char
return plain_text
```
使用示例:
```python
plain_text = "This is a test message."
key = "secret"
cipher_text = encrypt_vigenere(plain_text, key)
print(cipher_text)
# Output: "Ksgd dn s wuwp aowrrya."
decrypted_text = decrypt_vigenere(cipher_text, key)
print(decrypted_text)
# Output: "This is a test message."
```
该代码实现了维吉尼亚加密和解密函数,其中加密函数接受明文和密钥作为输入,并返回密文,解密函数接受密文和密钥作为输入,并返回原始明文。
阅读全文