天使漫步IT工作室天使漫步IT工作室

【代码片段】RSA算法代码实现(Python)


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

1、什么是RSA

RSA算法是现今使用最广泛的公钥密码算法,也是号称地球上最安全的加密算法。在了解RSA算法之前,先熟悉下几个术语
根据密钥的使用方法,可以将密码分为对称密码和公钥密码
对称密码:加密和解密使用同一种密钥的方式
公钥密码:加密和解密使用不同的密码的方式,因此公钥密码通常也称为非对称密码。

更多信息请参考:
RSA算法原理
带你彻底理解RSA算法原理

2、代码实现

import random
import math

#产生p,q,N,L,E三个数值
def primeNum():
    p=random.randrange(10,90)
    q=random.randrange(10,90)
    p=isPrime(p)
    q=isPrime(q)
    while p==False:
        p=random.randrange(10,90)
        p=isPrime(p)
    while q==False:
        q=random.randrange(10,90)
        q=isPrime(q)
    N=p*q
    L=lcm(p-1,q-1)
    e=random.randrange(1,L)
    e=iszhishu(e,L)
    while e==False:
        e=random.randrange(1,L)
        #print(1)
        e=iszhishu(e,L)
    #公钥为(e,N)
    #接下来求私钥D: 1<D<L,且E*DmodL=1
    D=random.randrange(1,L)
    D=ismo(D*e,L)
    while D==False:
        D=random.randrange(1,L)
        D=ismo(D*e,L)
    #私钥为(int(D/e),N)
    return p,q,N,L,e,int(D/e)
#判断两个数相mod为一
def ismo(a,b):
    if a%b==1:
        return a
    else:
        return False
#求两个数的最小公倍数
def lcm(p,q):
    if p>q:
        max=p
        min=q
    elif p<q:
        max=q
        min=p
    else:
        return p
    for i in range(1,min+1):
        num=max*i
        if num%p==0 and num%q==0:
            return num
#判断两个数是否为互为质数
def iszhishu(e,L):
    a=e
    b=L
    while a>1:
        tmp=b%a
        if tmp==0:
            return False
        else:
            b=a
            a=tmp
    return e

#判断随机产生的p,q是否为素数
def isPrime(num):
    j=math.sqrt(num)
    for i in range(2,int(j)+2):
        if num%i==0:
            return False
    return num
#加密
def jiami(e,N):
    mw=input("请输入明文(仅限数字):")
    mw=int(mw)
    secret=pow(mw,e)%N
    return secret 
#解密
def jiemi(D,secret,N):
    mw=pow(secret,D)%N
    return mw
if __name__=='__main__':
    p,q,N,L,e,D=primeNum()
    print(p,q,N,L,e,D)
    secret=jiami(e,N)
    print("加密之后密文为:",secret)
    secret=int(input("请输入密文:"))
    mw=jiemi(D,secret,N)
    print("解密之后明文为:",mw)
    

the end

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » 【代码片段】RSA算法代码实现(Python)
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38