维吉尼亚密码python实现
时间: 2023-05-29 07:03:31 浏览: 331
python3.6+维吉尼亚密码解密解密词频统计唯密文攻击+tkinter工具
以下是维吉尼亚密码的Python实现:
```python
def encrypt_vigenere(plaintext, key):
# 将明文和密钥都转换为大写字母
plaintext = plaintext.upper()
key = key.upper()
# 将密钥重复,直到与明文长度相等
while len(key) < len(plaintext):
key += key
# 加密过程
ciphertext = ""
for i in range(len(plaintext)):
char = plaintext[i]
key_char = key[i]
if char.isalpha():
# 计算字符与A的偏移量
char_offset = ord(char) - ord('A')
key_offset = ord(key_char) - ord('A')
# 计算加密后的字符偏移量
cipher_offset = (char_offset + key_offset) % 26
# 计算加密后的字符并添加到密文中
cipher_char = chr(cipher_offset + ord('A'))
ciphertext += cipher_char
else:
# 如果字符不是字母,则直接添加到密文中
ciphertext += char
return ciphertext
def decrypt_vigenere(ciphertext, key):
# 将密文和密钥都转换为大写字母
ciphertext = ciphertext.upper()
key = key.upper()
# 将密钥重复,直到与密文长度相等
while len(key) < len(ciphertext):
key += key
# 解密过程
plaintext = ""
for i in range(len(ciphertext)):
char = ciphertext[i]
key_char = key[i]
if char.isalpha():
# 计算字符与A的偏移量
char_offset = ord(char) - ord('A')
key_offset = ord(key_char) - ord('A')
# 计算解密后的字符偏移量
plain_offset = (char_offset - key_offset) % 26
# 计算解密后的字符并添加到明文中
plain_char = chr(plain_offset + ord('A'))
plaintext += plain_char
else:
# 如果字符不是字母,则直接添加到明文中
plaintext += char
return plaintext
```
使用示例:
```python
plaintext = "HELLO WORLD"
key = "KEY"
ciphertext = encrypt_vigenere(plaintext, key)
print(ciphertext) # "RIJVS UYVJN"
decrypted_plaintext = decrypt_vigenere(ciphertext, key)
print(decrypted_plaintext) # "HELLO WORLD"
```
阅读全文