玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python对RSA算法的简单实现

Python对RSA算法的简单实现。这是一段关于python算法的相关源码示例。

什么是RSA算法?它是由三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字命名,叫做RSA算法。

需要python importpython math 模块方法。

#!/usr/bin/env python  
#-*-coding: utf-8-*-  
 
import math  

def isPrime(number):  
    i=2  
    sqrtNumber=int(math.sqrt(number))  
    for i in range(2, sqrtNumber+1):  
        if number%i == 0:  
            return False  
        i = i+1  
    return True  
  
if __name__=="__main__":  
    print "*"*77  
    Flag = False  

    while Flag == False:  
        p = int(raw_input("Please input a prime(P): "))  
        Flag = isPrime(p)  
        if Flag == False:  
            print "What you input is not a prime!"  
    print "The P is: ", p  
      
    Flag = False  

    while Flag == False:  
        q = int(raw_input("Please input a prime(Q): "))  
        if p == q:  
            continue  
        Flag = isPrime(q)  
        if Flag == False:  
            print "What you input is not a prime!"  
    print "The Q is: ", q  
    n = p*q  

    print "The N is: ", n  
    t = (p-1)*(q-1)  

    print "The T is: ", t  
      
    print "*"*77  

    Flag = False  

    while Flag == False:  
        e = int(raw_input("Please input a number(E): "))  
        if (e<1 or e>t):  
            continue  
        d=0  
        while (((e*d)%t) != 1):  
            d+=1  
        Flag = True  
    print "The E is: ", e  
    print "The D is: ", d  
    print "The Public Key(E, N) is:", e, n  
    print "The Private Key(D, N) is:", d, n  
  
#www.iplaypy.com

    print "*"*77  
    Flag = False  

    while Flag == False:  
        plainText = int(raw_input("Please input a plaintext: "))  
        if (plainText < n):  
            Flag = True  
    print "The plaintext is: ", plainText  
    print "Encrypt"+"."*7  

    cipherText = (plainText**e)%n   

    print "cipherText is: ", cipherText   
    print "Decrypt"+"."*7  
    plain = (cipherText**d)%n  
    print "The plain is: ", plain  
  
    print "*"*77  

    if plainText == plain:  
        print "RSA Test success."  
    else:  
        print "RSA Test unsuccess!" 

玩蛇网文章,转载请注明出处和文章网址:http://www.iplaypy.com/code/algorithm/a2543.html [复制]



我要小额赞助,鼓励作者写出更好的教程↓↓↓

玩蛇网Python QQ群,欢迎加入: ① 279974227 玩蛇网Python新手群
修订日期:2016年04月05日 - 20时50分09秒 发布自玩蛇网

我要分享到:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
站长推荐:
去顶部去底部