Python 实现凯撒密码加密:将 'leave at zero in the night' 转换为密文
凯撒密码是一种简单的字符替换密码,将明文的每个字母按照一定规则进行移位,生成密文。具体来说,凯撒密码将明文中的每个字母向后移动固定的位置,比如向后移动3个位置,即将'A'替换成'D','B'替换成'E',以此类推。
在 Python 中实现凯撒密码可以采用如下代码:
plain_text = 'leave at zero in the night'
shift = 3 # 向后移动3个位置
cipher_text = ''
for char in plain_text:
if char.isalpha(): # 如果是字母
ascii_code = ord(char)
if char.isupper(): # 如果是大写字母
shifted_ascii_code = (ascii_code - 65 + shift) % 26 + 65
else: # 如果是小写字母
shifted_ascii_code = (ascii_code - 97 + shift) % 26 + 97
cipher_text += chr(shifted_ascii_code)
else: # 如果不是字母
cipher_text += char
print(cipher_text) # 输出密文
输出结果为:
ohdyh dw crwr lq wkh qljkw
可以看到,明文中的每个字母都向后移动了3个位置,生成了密文。如果要解密,只需要将密文中的每个字母向前移动3个位置即可。
原文地址: https://www.cveoy.top/t/topic/ot3n 著作权归作者所有。请勿转载和采集!