凯撒密码详解:原理、加密方法和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 croru lq wkh qljkw'
Python代码实现:
def caesar_cipher(plaintext, shift):
ciphertext = ''
for char in plaintext:
if char.isalpha():
if char.isupper():
ciphertext += chr((ord(char) - 65 + shift) % 26 + 65)
else:
ciphertext += chr((ord(char) - 97 + shift) % 26 + 97)
else:
ciphertext += char
return ciphertext
plaintext = 'leave at zero in the night'
shift = 3
ciphertext = caesar_cipher(plaintext, shift)
print(ciphertext)
输出结果为:'ohdyh dw croru lq wkh qljkw'
原文地址: https://www.cveoy.top/t/topic/fWIb 著作权归作者所有。请勿转载和采集!