算法:凯撒密码问题:通过把字母移动一定的位数来实现加密和解密。

凯撒密码问题:通过把字母移动一定的位数来实现加密和解密。

例如(移动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

你可能感兴趣的:(算法,密码学,加密解密,python)