改进上面这段代码
时间: 2023-08-06 09:26:26 浏览: 37
可以对上面的维吉尼亚密码加密代码进行一些改进,使其更加健壮和通用。以下是改进的代码:
```python
import random
def generate_random_text(length):
# 生成随机明文
text = ""
for i in range(length):
text += chr(random.randint(ord('A'), ord('Z')))
return text
def vigenere_cipher(text, key):
# 将明文和密钥转换为大写字母
text = text.upper()
key = key.upper()
# 检查密钥是否合法
if not key.isalpha():
raise ValueError("密钥只能包含字母")
# 初始化密文和密钥索引
cipher = ""
key_index = 0
# 遍历明文中的每个字符
for char in text:
if char.isalpha():
# 计算字符的偏移量
offset = ord(key[key_index]) - ord('A')
key_index = (key_index + 1) % len(key)
# 加密字符
if char.isupper():
cipher += chr((ord(char) - ord('A') + offset) % 26 + ord('A'))
else:
cipher += chr((ord(char) - ord('a') + offset) % 26 + ord('a'))
else:
# 不加密非字母字符
cipher += char
return cipher
# 生成随机明文并加密
text = generate_random_text(10)
key = "SECRETKEY"
cipher = vigenere_cipher(text, key)
# 输出明文和密文
print("明文:", text)
print("密文:", cipher)
```
改进后的代码增加了对生成随机明文的函数 `generate_random_text` 的改进,使用了 `ord` 函数获取大写字母 `A` 和 `Z` 的 ASCII 码,避免了硬编码。同时,为了避免在加密过程中出现错误,增加了对密钥的合法性检查,只允许密钥包含字母。如果密钥不合法,将会抛出一个 `ValueError` 异常。