1

我正在做欧几里得算法和乘法逆的前一个线程问题,然后我明白最好发布完整的代码并做正确的问题:我正在执行 python rsa 实现并需要修复它,因为它输出错误的结果。

编码:

import fractions  #gcd

def generateRSAKeys(p, q):
    "Generate RSA Public and Private Keys from prime numbers p & q"

    n = p * q #is used as the modulus for both the public and private keys
    etf = (p - 1) * (q - 1) #Euler's totient function.  etf   

    # Generate a number e so that gcd(n, e) = 1, start with e = 3
    e = 3

    while 1:
        if fractions.gcd(e, etf) == 1 and 1<e and e<etf: 
            break  
        else: 
            e = e + 1 

    #e is released as the public key exponent.
    # start with a number d = etf/e will be atleast 1


    #e*d == 1%etf  #multiplicative inverse of etf   
    d = (e**(etf-2)) % etf 

    # Return a tuple of public and private keys 
    return ((n,e), (n,d))           

    #http://en.wikipedia.org/wiki/RSA_%28algorithm%29

if __name__ == "__main__":

    print "RSA Encryption algorithm...."
    p = long(raw_input("Enter the value of p (prime number):"))
    q = long(raw_input("Enter the value of q (prime number):"))

    print "Generating public and private keys...."
    (publickey, privatekey) = generateRSAKeys(p, q)

    print "Public Key (n, e) =", publickey
    print "Private Key (n, d) =", privatekey

    n, e = publickey
    n, d = privatekey

    m = 34 #some message

    print "0<m<n m=", m
    print "0<m<n n=" , n
    #then computes ciphertext c
    c = (m**e)%n
    print "Encrypted number using public key =", c
    #recovering
    m = (c**d)%n
    print "Decrypted (Original) number using private key =", m
4

0 回答 0