python123维吉尼亚密码
时间: 2023-08-31 14:12:51 浏览: 105
维吉尼亚密码是一种经典的多表代换密码,它使用一个加密关键字对明文进行加密。下面是一个简单的 Python 代码实现维吉尼亚密码:
```python
def encrypt_vigenere(plaintext, key):
ciphertext = ""
key = key.upper()
for i in range(len(plaintext)):
shift = ord(key[i % len(key)]) - 65
if plaintext[i].isalpha():
if plaintext[i].islower():
ciphertext += chr((ord(plaintext[i]) - 97 + shift) % 26 + 97)
else:
ciphertext += chr((ord(plaintext[i]) - 65 + shift) % 26 + 65)
else:
ciphertext += plaintext[i]
return ciphertext
def decrypt_vigenere(ciphertext, key):
plaintext = ""
key = key.upper()
for i in range(len(ciphertext)):
shift = ord(key[i % len(key)]) - 65
if ciphertext[i].isalpha():
if ciphertext[i].islower():
plaintext += chr((ord(ciphertext[i]) - 97 - shift) % 26 + 97)
else:
plaintext += chr((ord(ciphertext[i]) - 65 - shift) % 26 + 65)
else:
plaintext += ciphertext[i]
return plaintext
```
使用方法:
```python
plaintext = "HELLO WORLD"
key = "SECRET"
ciphertext = encrypt_vigenere(plaintext, key)
print(ciphertext)
decrypted_text = decrypt_vigenere(ciphertext, key)
print(decrypted_text)
```
输出结果:
```
DPLZS QIVVY
HELLO WORLD
```
其中,`encrypt_vigenere` 函数用于加密明文,`decrypt_vigenere` 函数用于解密密文。
阅读全文