58 lines
1.6 KiB
Python
58 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
凯撒加密算法示例
|
|
一个教学用的凯撒密码实现
|
|
"""
|
|
|
|
def caesar_encrypt(plaintext, shift):
|
|
"""凯撒加密函数"""
|
|
ciphertext = ""
|
|
|
|
for char in plaintext:
|
|
if char.isalpha():
|
|
base = ord('A') if char.isupper() else ord('a')
|
|
new_char = chr((ord(char) - base + shift) % 26 + base)
|
|
ciphertext += new_char
|
|
else:
|
|
ciphertext += char
|
|
|
|
return ciphertext
|
|
|
|
def caesar_decrypt(ciphertext, shift):
|
|
"""凯撒解密函数"""
|
|
return caesar_encrypt(ciphertext, -shift)
|
|
|
|
def main():
|
|
"""主函数,用户交互界面"""
|
|
print("凯撒密码示例")
|
|
|
|
while True:
|
|
print("\n1.加密\n2.解密\n3.退出")
|
|
choice = input("选择: ").strip()
|
|
|
|
if choice == "1":
|
|
text = input("明文: ")
|
|
try:
|
|
shift = int(input("移位值: "))
|
|
result = caesar_encrypt(text, shift)
|
|
print(f"密文: {result}")
|
|
except ValueError:
|
|
print("移位值必须是整数!")
|
|
|
|
elif choice == "2":
|
|
text = input("密文: ")
|
|
try:
|
|
shift = int(input("移位值: "))
|
|
result = caesar_decrypt(text, shift)
|
|
print(f"明文: {result}")
|
|
except ValueError:
|
|
print("移位值必须是整数!")
|
|
|
|
elif choice == "3":
|
|
print("再见!")
|
|
break
|
|
else:
|
|
print("无效选择")
|
|
|
|
if __name__ == "__main__":
|
|
main() |