密码学:基于python的rsa算法

#n=p和q随机生成

#课本以两个字母为一组,此处以每一个字母为一组,故必须n=p*q>2

import math

import random

dict1={‘a’:0,’b’:1,’c’:2,’d’:3,’e’:4,’f’:5,’g’:6,’h’:7,’i’:8,’j’:9,’k’:10,’l’:11,’m’:12,’n’:13,’o’:14,’p’:15,’q’:16,’r’:17,’s’:18,’t’:19,’u’:20,’v’:21,’w’:22,’x’:23,’y’:24,’z’:25} #字典键值转换

dict2 = dict(zip(dict1.values(),dict1))

#生成100以内的素数数组

def prime_array():

    array = []

    for i in range(2,1000):

        x = prime(i,2)

        if x :

            array.append(i)

    return array

   

#判断素数

def prime(n,div):

    if math.sqrt(n) < div:

        return True

    if n % div == 0:

        return False

    else :

        return prime(n,div + 1) #求最大公约数

def gcd(a,b):

    if b == 0:

        return a

    else :

        return gcd(b,a%b)

#找出与(p-1)*(p+1)互质的素数e

def co_prime(s):

    while True:

        e = random.choice(range(100))

        x = gcd(e,s)

        if x == 1:

            break

    return e

#找出d

def find_d(e,s):

    d = 0

    while(True):

        d += 1

        x = (e * d) % s

        if x == 1:

            return d

#加密

def encryption(m,ku):

    C = pow(m,ku[0]) % ku[1]

    return C

#解密

def decode(c,kr):

    M = pow(c,kr[0]) % kr[1]

    return M

#主函数

if __name__ == ‘__main__’:

   # print(“字典1:”,dict1,”\n”+”字典2″,dict2)

    print(‘请输入明文(只支持小写字母):’)

    M = input()

    C = “”

    iC = []

    print(“p,q的取值范围:”)

    array = prime_array()

    print(array) #n不能小于25

    while True:

        p = random.choice(array)

        q = random.choice(array)

        n = p * q

        if n>25:

            break

    print(‘p为{},q为{}’.format(p,q))     s = (p-1) * (q-1)

    e = co_prime(s)

    d = find_d(e,s)

    KU = [e,n]

    KR = [d,n]

#加密结果

    for ch in M:

        iC.append(encryption(dict1[ch],KU))

    for i in iC:

        C += str(i)

    print(“加密后密文为:”,C)

#解密结果

    M = ”

    for i in iC:

        M += dict2[decode(i,KR)]

    print(‘解密后明文为:’,M)

点赞