RSA算法研究與PYTHON實現

RSA算法是一種非對稱密碼算法,所謂非對稱,就是指該算法需要一對密鑰,使用其中一個加密,則需要用另一個才能解密。
RSA的算法涉及三個參數,n、e1、e2。
其中,n是兩個大質數p、q的積,n的二進制表示時所佔用的位數,就是所謂的密鑰長度。
e1和e2是一對相關的值,e1可以任意取,但要求e1與(p-1)*(q-1)互質;再選擇e2,要求(e2*e1)mod((p-1)*(q-1))=1。
(n,e1),(n,e2)就是密鑰對。其中 (n,e1)爲公鑰,(n,e2)爲私鑰
RSA加解密的算法完全相同,設A爲明文,B爲密文,則:A=B^e1 mod n;B=A^e2 mod n;
e1和e2可以互換使用,即:
A=B^e2 mod n;B=A^e1 mod n;

RSA用到的公式和定理
一、數和互爲素數
任何大於1的整數a能被因式分解爲如下唯一形式:
a=p1p2…pl(p1,p2,…,pl爲素數)
二、模運算
①{[a(modn)]×[b(mod n)]}modn≡(a×b)(mod n)
②如果(a×b)=(a×c)(mod n),a與n互素,則
b=c(mod n)
三、費馬定理
若p是素數,a與p互素,則
a^(p-1)=1 mod p
四、歐拉定理
歐拉函數φ(n)表示不大於n且與n互素的正整數的個數。
當n是素數,φ(n)=n-1。n=pq,p,q均爲素數時,則φ(n)= φ(p)φ(q)=(p-1)(q-1)。
對於互素的a和n,有a^φ(n)=1(mod n)



def isPrime(number):
    import math
    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  
  
    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!" 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章