Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

duplicated code in Python_RSAKey #427

Open
tomato42 opened this issue Oct 18, 2020 · 0 comments
Open

duplicated code in Python_RSAKey #427

tomato42 opened this issue Oct 18, 2020 · 0 comments
Labels
good first issue relatively simple changes, good for first time contributors help wanted

Comments

@tomato42
Copy link
Member

tomato42 commented Oct 18, 2020

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.

@tomato42 tomato42 added help wanted good first issue relatively simple changes, good for first time contributors labels Oct 18, 2020
@tomato42 tomato42 added this to the someday/future milestone Oct 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue relatively simple changes, good for first time contributors help wanted
Projects
None yet
Development

No branches or pull requests

1 participant