vigenere密码算法python
时间: 2023-10-24 08:17:42 浏览: 141
Vigenere密码算法是一种基于多表加密的加密算法,它的原理是通过使用一个关键字来对明文进行多次加密,使得密文更加难以被解密。以下是一个使用Python实现Vigenere密码算法的示例代码:
```python
def vigenere_encrypt(plaintext, key):
# 生成密文表
cipher_table = []
for i in range(26):
row = []
for j in range(26):
row.append(chr((i + j) % 26 + 65))
cipher_table.append(row)
# 将明文和密钥转换为大写
plaintext = plaintext.upper()
key = key.upper()
# 对明文进行加密
ciphertext = ""
key_index = 0
for letter in plaintext:
if letter.isalpha():
row = ord(key[key_index]) - 65
col = ord(letter) - 65
ciphertext += cipher_table[row][col]
key_index = (key_index + 1) % len(key)
else:
ciphertext += letter
return ciphertext
def vigenere_decrypt(ciphertext, key):
# 生成密文表
cipher_table = []
for i in range(26):
row = []
for j in range(26):
row.append(chr((i + j) % 26 + 65))
cipher_table.append(row)
# 将密文和密钥转换为大写
ciphertext = ciphertext.upper()
key = key.upper()
# 对密文进行解密
plaintext = ""
key_index = 0
for letter in ciphertext:
if letter.isalpha():
row = ord(key[key_index]) - 65
col = cipher_table[row].index(letter)
plaintext += chr(col + 65)
key_index = (key_index + 1) % len(key)
else:
plaintext += letter
return plaintext
```
使用示例:
```python
plaintext = "HELLO WORLD"
key = "SECRET"
ciphertext = vigenere_encrypt(plaintext, key)
print("密文:", ciphertext)
plaintext = vigenere_decrypt(ciphertext, key)
print("明文:", plaintext)
```
输出结果:
```
密文: DDLXWYHXGZ
明文: HELLOWORLD
```
阅读全文