Skip to content

duplicated code in Python_RSAKey #427

@tomato42

Description

@tomato42

The code in __init__:

def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0,
key_type="rsa"):
"""Initialise key directly from integers.
see also generate() and parsePEM()."""
if (n and not e) or (e and not n):
raise AssertionError()
if gmpyLoaded or GMPY2_LOADED:
n = mpz(n)
e = mpz(e)
d = mpz(d)
p = mpz(p)
q = mpz(q)
dP = mpz(dP)
dQ = mpz(dQ)
qInv = mpz(qInv)
self.n = n
self.e = e
if p and not q or not p and q:
raise ValueError("p and q must be set or left unset together")
if not d and p and q:
t = lcm(p - 1, q - 1)
d = invMod(e, t)
self.d = d
self.p = p
self.q = q
if not dP and p:
dP = d % (p - 1)
self.dP = dP
if not dQ and q:
dQ = d % (q - 1)
self.dQ = dQ
if not qInv:
qInv = invMod(q, p)
self.qInv = qInv
self.blinder = 0
self.unblinder = 0
self._lock = threading.Lock()
self.key_type = key_type

and the code in generate():
@staticmethod
def generate(bits, key_type="rsa"):
"""Generate a private key with modulus 'bits' bit big.
key_type can be "rsa" for a universal rsaEncryption key or
"rsa-pss" for a key that can be used only for RSASSA-PSS."""
key = Python_RSAKey()
p = getRandomPrime(bits//2, False)
q = getRandomPrime(bits//2, False)
if gmpyLoaded or GMPY2_LOADED:
p = mpz(p)
q = mpz(q)
t = lcm(p-1, q-1)
key.n = p * q
if gmpyLoaded or GMPY2_LOADED:
key.e = mpz(65537)
else:
key.e = 65537
key.d = invMod(key.e, t)
key.p = p
key.q = q
key.dP = key.d % (p-1)
key.dQ = key.d % (q-1)
key.qInv = invMod(q, p)
key.key_type = key_type
return key

perform the same operations. generate() could be reduced to calculating just p, q, n, and selecting e, passing them to Python_RSAKey constructor, so that __init__ calculates the d, dP, dQ, and qInv.

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issuerelatively simple changes, good for first time contributorshelp wanted

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions