凯撒密码的加密和解密功能都加入循环偏移量
时间: 2023-08-11 08:08:48 浏览: 38
如果你想实现凯撒密码的加密和解密功能都加入循环偏移量,可以进行如下修改:
```python
def caesar_encrypt(plaintext, shift):
ciphertext = ""
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) + shift - 65) % 26 + 65)
else:
ciphertext += chr((ord(char) + shift - 97) % 26 + 97)
else:
ciphertext += char
return ciphertext
def caesar_decrypt(ciphertext, shift):
plaintext = ""
for char in ciphertext:
if char.isalpha():
if char.isupper():
plaintext += chr((ord(char) - shift - 65) % 26 + 65)
else:
plaintext += chr((ord(char) - shift - 97) % 26 + 97)
else:
plaintext += char
return plaintext
text = input("输入要加密/解密的文本: ")
choice = input("加密或解密? (e/d): ")
if choice == "e":
for shift in range(26):
ciphertext = caesar_encrypt(text, shift)
print(f"Shift = {shift:>2} | Ciphertext: {ciphertext}")
elif choice == "d":
for shift in range(26):
plaintext = caesar_decrypt(text, shift)
print(f"Shift = {shift:>2} | Plaintext: {plaintext}")
else:
print("无效的选择。请输入 'e' 或 'd' 来选择加密或解密。")
```
这段代码在主程序部分进行了修改,根据用户的选择进行加密或解密。如果选择加密,代码会使用一个循环来尝试所有可能的偏移量,然后打印出每个偏移量对应的密文。如果选择解密,同样会使用一个循环来尝试所有可能的偏移量,然后打印出每个偏移量对应的明文。
运行这段代码时,你需要输入要加密/解密的文本和选择加密或解密。然后程序会尝试所有可能的偏移量,并打印出每个偏移量对应的加密或解密结果。
请注意,这里的循环偏移量是在范围0到25内进行的,因为凯撒密码只有26个可能的偏移量。如果你想扩展为更大的偏移量范围,可以修改循环的范围。