凯撒密码最早由古罗马军事统帅盖乌斯·尤利乌斯·凯撒在军队中用来传递加密信息故称凯撒密码。这是一种位移加密方式只对26个字母进行位移替换加密规则简单容易破解。若将明文字母表向后移动3位:明文字母表XYZABCDEFGHIJKLMNOPQRSTUVW密文字母表ABCDEFGHIJKLMNOPQRSTUVWXYZ则A变成了DB变成了E……Z变成了C。字母表最多可以移动25位。凯撒密码的明文字母表向后或向
明文:leave at zero in the night
将明文字母表向后移动3位,得到密文字母表
加密后的密文为:ohdyh dw croru lq wkh qljkw
用Python实现:
# 定义明文字母表和密文字母表
plaintext_alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext_alphabet = "defghijklmnopqrstuvwxyzabc"
# 定义明文
plaintext = "leave at zero in the night"
# 加密函数
def caesar_cipher_encrypt(plaintext, alphabet, shift):
ciphertext = ""
for char in plaintext:
if char in alphabet:
# 获取明文字母表中的位置
index = alphabet.index(char)
# 根据位移获取密文字母表中的位置
new_index = (index + shift) % len(alphabet)
# 获取密文字母表中对应位置的字母
new_char = alphabet[new_index]
# 添加到密文中
ciphertext += new_char
else:
# 对于非字母字符直接添加到密文中
ciphertext += char
return ciphertext
# 调用加密函数,将明文加密为密文
ciphertext = caesar_cipher_encrypt(plaintext, plaintext_alphabet, 3)
# 输出密文
print(ciphertext) # 输出:ohdyh dw croru lq wkh qljkw
``
原文地址: https://www.cveoy.top/t/topic/fFFK 著作权归作者所有。请勿转载和采集!