凯撒密码说明
例如(移动3格):a-D、b-E、 c-F、d-G、e-H … … s-V … …、z-C
明文:access control
可变为: DFFHVV FRQWURO
代码
import random
def Letter_num(Letter): # a-z转换为0-25
return ord(Letter) - 97
def num_Letter(num): # 0-25转换为a-z
return chr(num + 97)
def encryption_Letter(P, K): # 加密单个字母
C = num_Letter((Letter_num(P) + K) % 26)
return C
def Decrypt_Letter(C, K): # 解密单个字母
P = num_Letter((Letter_num(C) - K) % 26)
return P
def encryption_fun(P_char, K): # 加密字符串
C_char = ''
for P in P_char:
if P.isalpha():
P = encryption_Letter(P, K)
C_char = C_char + P
return C_char
def Decrypt_fun(C_char, K): # 解密字符串
P_char = ''
for C in C_char:
if C.isalpha():
C = Decrypt_Letter(C, K)
P_char = P_char + C
return P_char
if __name__ == '__main__':
K = int(random.random()*26%26)
P_text = "let's meet after the party.if you understand this sentence, the program runs successfully.abcd efghjgkl mnopqr stu vwxy z"
print('原文为:',P_text)
print('K:',K)
C_text = encryption_fun(P_text, K)
print('密文为:', C_text)
PP_text = Decrypt_fun(C_text, K)
print('解密后是:', PP_text)
结果
原文为: let's meet after the party.if you understand this sentence, the program runs successfully.abcd efghjgkl mnopqr stu vwxy z
K: 14
密文为: zsh'g assh othsf hvs dofhm.wt mci ibrsfghobr hvwg gsbhsbqs, hvs dfcufoa fibg giqqsggtizzm.opqr stuvxuyz abcdef ghi jklm n
解密后是: let's meet after the party.if you understand this sentence, the program runs successfully.abcd efghjgkl mnopqr stu vwxy z