以下是一个Python代码示例,展示如何实现Caesar加密和解密:
# Caesar加密函数
def caesar_encrypt(text, shift):
result = ""
# 循环遍历输入的字符串中的每个字符
for i in range(len(text)):
# 判断字符是否为大写字母
if text[i].isupper():
# 通过ASCII码值实现加密
result += chr((ord(text[i]) + shift - 65) % 26 + 65)
# 判断字符是否为小写字母
elif text[i].islower():
result += chr((ord(text[i]) + shift - 97) % 26 + 97)
else:
result += text[i] # 将非字母字符直接添加到结果字符串中
return result
# Caesar解密函数
def caesar_decrypt(text, shift):
result = ""
for i in range(len(text)):
if text[i].isupper():
# 通过ASCII码值实现解密
result += chr((ord(text[i]) - shift - 65) % 26 + 65)
elif text[i].islower():
result += chr((ord(text[i]) - shift - 97) % 26 + 97)
else:
result += text[i] # 将非字母字符直接添加到结果字符串中
return result
# 使用示例
text = "Hello, World!"
shift = 3
encrypted_text = caesar_encrypt(text, shift)
print(encrypted_text)
# 输出:Khoor, Zruog!
decrypted_text = caesar_decrypt(encrypted_text, shift)
print(decrypted_text)
# 输出:Hello, World!
在上述代码示例中,我们首先定义了一个Caesar加密函数caesar_encrypt()
和一个Caesar解密函数caesar_decrypt()
。这两个函数都接受两个参数:需要加密/解密的文本和移位数。
在加密函数中,我们使用了ord()函数和chr()函数。通过将字符转换