凱撒密碼問題:通過把字母移動一定的位數來實作加密和解密,
例如(移動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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/251771.html
標籤:python
