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

Python对RSA算法的简单实现

python 培训

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.iplaypython.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.iplaypython.com/code/algorithm/a2543.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-04-05 20:50 玩蛇网 www.iplaypython.com

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