vigenere算法编程实例
时间: 2023-12-23 21:27:33 浏览: 76
JavaScript实现维吉尼亚(Vigenere)密码算法实例
以下是一个使用维吉尼亚算法进行加密和解密的Python编程实例:
```python
def vigenere_encrypt(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
key_char = key[key_index % len(key)]
if char.isupper():
base = ord('A')
else:
base = ord('a')
encrypted_char = chr((ord(char) - base + ord(key_char) - base) % 26 + base)
ciphertext += encrypted_char
key_index += 1
else:
ciphertext += char
return ciphertext
def vigenere_decrypt(ciphertext, key):
plaintext = ""
key_index = 0
for char in ciphertext:
if char.isalpha():
key_char = key[key_index % len(key)]
if char.isupper():
base = ord('A')
else:
base = ord('a')
decrypted_char = chr((ord(char) - base - (ord(key_char) - base) + 26) % 26 + base)
plaintext += decrypted_char
key_index += 1
else:
plaintext += char
return plaintext
plaintext = "COMPUTER"
key = "ACM"
ciphertext = vigenere_encrypt(plaintext, key)
print("加密后的密文:", ciphertext)
decrypted_plaintext = vigenere_decrypt(ciphertext, key)
print("解密后的明文:", decrypted_plaintext)
```
输出结果:
```
加密后的密文: CQYXZQXU
解密后的明文: COMPUTER
```
阅读全文