代码之家  ›  专栏  ›  技术社区  ›  amwinter

针对RSA算法的python包

  •  3
  • amwinter  · 技术社区  · 15 年前

    希望在python中对短字符串进行RSA加密。这是为了一个用户数据,我想存储没有工作人员(包括我自己)能够看到它。私人钥匙会放在我的保险箱里的拇指驱动器上,等我们被传唤时用。

    我的问题: 对于非对称密钥RSA,是否有“可能正确”的python包?使用C库更安全吗(如果是的话,是哪个库)。

    4 回复  |  直到 13 年前
        1
  •  1
  •   Omnifarious    15 年前

    使用RSA加密短字符串可能有问题。您可以使用RSA加密某些数据,这些数据可以显示有关您的私钥的详细信息。在您的情况下,这可能是好的,因为它将足够模糊,您的工作人员不会发现它。但是,在一般情况下,对于一个知识渊博和/或资金充足的对手,如果您希望将数据保密,则不希望使用RSA直接加密数据。

    我建议你只用 gnupg 相反。它帮你解决了所有的问题。

        2
  •  3
  •   Barry Wark    15 年前
        3
  •  2
  •   unutbu    15 年前
        4
  •  1
  •   Tim Cooper    13 年前
    def gcd (a, b):
        "Compute GCD of two numbers"
    
        if b == 0: return a
        else: return gcd(b, a % b)
    
    def multiplicative_inverse(a, b):
        """ Find multiplicative inverse of a modulo b (a > b)
            using Extended Euclidean Algorithm """
    
        origA = a
        X = 0
        prevX = 1
        Y = 1
        prevY = 0
    
        while b != 0:
    
            temp = b
            quotient = a/b
            b = a % b
            a = temp
    
            temp = X
            a = prevX - quotient * X
            prevX = temp
    
            temp = Y
            Y = prevY - quotient * Y
            prevY = temp
    
        return origA + prevY
    
    def generateRSAKeys(p, q):
        "Generate RSA Public and Private Keys from prime numbers p & q"
    
        n = p * q
        m = (p - 1) * (q - 1)
    
        # Generate a number e so that gcd(n, e) = 1, start with e = 3
        e = 3
    
        while 1:
    
            if gcd(m, e) == 1: break
            else: e = e + 2
    
        d = multiplicative_inverse(m, e)   
    
        # Return a tuple of public and private keys 
        return ((n,e), (n,d))           
    
    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
    
        input_num = long(raw_input("Enter a number to be encrypted:"))
        encrypted_num = (input_num ** e) % n
        print "Encrypted number using public key =", encrypted_num
        decrypted_num = encrypted_num ** d % n
        print "Decrypted (Original) number using private key =", decrypted_num