alirezaarzehgar
alirezaarzehgar

Reputation: 299

RSA validate p and q keys in python, python-rsa lib

UPDATE

I have a program to get two public and private keys for validate those keys.

Either those key are valid or not.

We assume that our keys are valid.

(pub , privateKey) = rsa.newkeys(1024)

However I have a relation for p, q and nlen.

This is our mathematical equation for p and q:

  1. The primes p and q shall be selected with the following constraints:

(a) (p–1) and (q–1) shall be relatively prime to the public exponent e.

(b) The private prime factor p shall be selected and shall satisfy

(a) condition passed successfully.

But I can't understand item (b).

In the other hands we said len(p) = len(q) = nlen/2.

nlen equal to size of module in bites.

Let's talk about this condition :

This codes are definitions of p, q, d, e and nlen.

p = privkey.p
q = privkey.q
d = privkey.d
e = privkey.e
nlen = privkey.n.bit_length()

We implemented our conditions with this code :

if not sqrt(2) * (2 ** ((nlen/2) - 1)) <= p <= (2 ** (nlen/2)) - 1:
     return "Invalid P prime number size"

And another conditions implemented with this following codes :

Check q len

if not sqrt(2) * (2 ** ((nlen/2) - 1)) <= q <= (2 ** (nlen/2)) - 1:
    return "Invalid Q prime number size"

Above conditions didn't match and their bodies ran.

Anyway this problem is true for decryption len condition.

Second condition passes successfully.

But first throw my written error to parent class.

This my code :


if not 2 ** (nlen/2) < d < lcm(p-1, q-1):
    return "Invalid decryption key"

But why ?

I think my problem related to nlen. cause everywhere i used nlen, my Tests didn't passed and failed.

I checked its values but i don't know what i can do for fixing this problem.

Upvotes: 1

Views: 1340

Answers (2)

alirezaarzehgar
alirezaarzehgar

Reputation: 299

This private and public keys are absolutely valid. but our conditions are true for a secure key.

We can use pycryptodome python library for increase our key tests security.

In this case we should create a key pair with those passphrases and load them with same passphrase in pycryptodome.

Upvotes: 0

Kesslwovv
Kesslwovv

Reputation: 652

I think you text is wrong because both prime factors are only used for calculations of the keys and not published. the following answer will check if the keys are valid, not if they are secure:

In order to check if two keys are valid, you need to have the following values:

  • p and q (prime numbers selected)
  • n (mod-number = p * q)
  • key1 and key2 (public and private key)
def is_valid(p, q, key1, key2, n):  # assuming p and q are actually prime
    if n != p * q:  # check if n is actually p * q
        return False
    num = (p - 1) * (q - 1)
    if (key1 * key2) % num != 1:  # check if keys are valid
        return False
    return True

Upvotes: 1

Related Questions