python123维吉尼亚密码——加密
时间: 2023-09-20 20:06:29 浏览: 80
维吉尼亚密码是一种古典密码,它是通过对明文中的每个字母按照一定规则进行替换来进行加密的。下面是用 Python 实现维吉尼亚密码加密的代码:
```python
def vigenere_encrypt(plaintext, key):
ciphertext = ""
key_index = 0
for char in plaintext:
if char.isalpha():
# 将明文中的字母按照一定规则替换
shift = ord(key[key_index % len(key)].upper()) - 65
cipher_char = chr((ord(char.upper()) - 65 + shift) % 26 + 65)
ciphertext += cipher_char
key_index += 1
else:
ciphertext += char
return ciphertext
```
其中,`plaintext` 是明文,`key` 是密钥。这个函数会将明文中的每个字母按照一定规则替换成密文中的字母。具体来说,它会使用密钥中的字母来生成一个偏移量,然后将明文中的字母向右移动这个偏移量个位置,得到密文中的字母。如果明文中的某个字符不是字母,则直接将它添加到密文中。
以下是一个使用这个函数进行加密的例子:
```python
plaintext = "HELLO WORLD"
key = "SECRET"
ciphertext = vigenere_encrypt(plaintext, key)
print(ciphertext) # 输出:"ZICVTWQNGR"
```
在这个例子中,我们使用密钥 "SECRET" 对明文 "HELLO WORLD" 进行加密,得到了密文 "ZICVTWQNGR"。