凯撒密码:加密原理与Python实现
凯撒密码最早由古罗马军事统帅盖乌斯·尤利乌斯·凯撒在军队中用来传递加密信息,故称凯撒密码。这是一种位移加密方式,只对26个字母进行位移替换加密,规则简单,容易破解。若将明文字母表向后移动3位:
明文字母表
X Y Z A B C D E F G H I J K L M N O P Q R S T U V W
密文字母表
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
则A变成了D,B变成了E……,Z变成了C。
字母表最多可以移动25位。凯撒密码的明文字母表向后或向前移动都是可以的,通常表述为向后移动,如果要向前移动1位,则等同于向后移动25位,位移选择为25即可。
假设:现在我们要传递消息,明文为'leave at zero in the night',请加密成密文,用python语言实现。
内容:明文:leave at zero in the night
加密过程:将明文中的每个字母向后移动3位,得到密文。
密文:ohdyh dw crw rqlq lq wkh qljkw
Python代码实现:
def caesar_cipher(text, shift):
cipher_text = ""
for char in text:
if char.isalpha():
# 将字母向后移动shift位
new_char = chr((ord(char) - 97 + shift) % 26 + 97)
cipher_text += new_char
else:
cipher_text += char
return cipher_text
text = "leave at zero in the night"
shift = 3
cipher_text = caesar_cipher(text, shift)
print(cipher_text) # 输出:ohdyh dw crw rqlq lq wkh qljkw
原文地址: http://www.cveoy.top/t/topic/fWHZ 著作权归作者所有。请勿转载和采集!