Esempio n. 1
0
 def _rsa_pri(self):
     p = self._decode_int(self._params['p'])
     q = self._decode_int(self._params['q'])
     d = self._decode_int(self._params['d'])
     dp = self._decode_int(self._params['dp'])
     dq = self._decode_int(self._params['dq'])
     qi = self._decode_int(self._params['qi'])
     return rsa.RSAPrivateNumbers(p, q, d, dp, dq, qi, self._rsa_pub())
Esempio n. 2
0
 def _rsa_pri(self, k):
     return rsa.RSAPrivateNumbers(self._decode_int(k['p']),
                                  self._decode_int(k['q']),
                                  self._decode_int(k['d']),
                                  self._decode_int(k['dp']),
                                  self._decode_int(k['dq']),
                                  self._decode_int(k['qi']),
                                  self._rsa_pub(k))
Esempio n. 3
0
 def _rsa_pri(self):
     p = self._decode_int(self.get('p'))
     q = self._decode_int(self.get('q'))
     d = self._decode_int(self.get('d'))
     dp = self._decode_int(self.get('dp'))
     dq = self._decode_int(self.get('dq'))
     qi = self._decode_int(self.get('qi'))
     return rsa.RSAPrivateNumbers(p, q, d, dp, dq, qi, self._rsa_pub())
Esempio n. 4
0
 def load_json(self, jkey):
     pubkey = rsa.RSAPublicNumbers(b642int(jkey['e']), b642int(jkey['n']))
     prikey = rsa.RSAPrivateNumbers(
         b642int(jkey['p']), b642int(jkey['q']), b642int(jkey['d']),
         b642int(jkey['dp']), b642int(jkey['dq']), b642int(jkey['qi']),
         pubkey)
     pkey = prikey.private_key(BACKEND)
     return pkey, {k: jkey[k] for k in ['kty', 'n', 'e']}
Esempio n. 5
0
    def construct(cls, n, e, d, p, q, dmp1, dmq1, iqmp):
        """Construct an RSA private key"""

        pub = rsa.RSAPublicNumbers(e, n)
        priv = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, pub)
        priv_key = priv.private_key(default_backend())

        return cls(priv_key, pub, priv)
Esempio n. 6
0
def load_jwks(jwks_obj):
    """
    Given a JWKS-formatted dictionary representing a private key,
    return a python-cryptography private key object
    """

    if jwks_obj['kty'] == "RSA":
        n = long_from_bytes(jwks_obj['n'])
        e = long_from_bytes(jwks_obj['e'])
        d = long_from_bytes(jwks_obj['d'])
        public_key_numbers = rsa.RSAPublicNumbers(
            e = e,
            n = n,
        )
        # If loading a partial key, we'll have to recalculate a
        # few of the relevant constants
        if ('p' not in jwks_obj) or ('q' not in jwks_obj):
            p, q = rsa.rsa_recover_prime_factors(n, e, d)
        else:
            p = long_from_bytes(jwks_obj['p'])
            q = long_from_bytes(jwks_obj['q'])
        if 'qi' not in jwks_obj:
            qi = rsa.rsa_crt_iqmp(p, q)
        else:
            qi = long_from_bytes(jwks_obj['qi'])
        if 'dp' not in jwks_obj:
            dmp1 = rsa.rsa_crt_dmp1(d, p)
        else:
            dmp1 = long_from_bytes(jwks_obj['dp'])
        if 'dq' not in jwks_obj:
            dmq1 = rsa.rsa_crt_dmq1(d, q)
        else:
            dmq1 = long_from_bytes(jwks_obj['dq'])
        private_key_numbers = rsa.RSAPrivateNumbers(
            p = p,
            q = q,
            d = d,
            dmp1 = dmp1,
            dmq1 = dmq1,
            iqmp = qi,
            public_numbers = public_key_numbers
        )
        return private_key_numbers.private_key(default_backend())
    elif jwks_obj['kty'] == 'EC':
        public_key_numbers = ec.EllipticCurvePublicNumbers(
            long_from_bytes(jwks_obj['x']),
            long_from_bytes(jwks_obj['y']),
            ec.SECP256R1()
        )
        private_key_numbers = ec.EllipticCurvePrivateNumbers(
            long_from_bytes(jwks_obj['d']),
            public_key_numbers
        )
        return private_key_numbers.private_key(default_backend())
    else:
        raise scitokens.scitokens.UnsupportedKeyException("Issuer public key not supported.")
Esempio n. 7
0
    def __init__(
        self,
        n: str,
        e: str,
        d: Optional[str] = None,
        p: Optional[str] = None,
        q: Optional[str] = None,
        dp: Optional[str] = None,
        dq: Optional[str] = None,
        qi: Optional[str] = None,
        **ignore,
    ) -> None:
        self._private = None
        self._public = None

        modulus = b64_to_int(n)
        public_exponent = b64_to_int(e)

        public = rsa.RSAPublicNumbers(public_exponent, modulus)
        self._public: RSA_PUBLIC = public.public_key(default_backend())

        if d:
            private_exponent = b64_to_int(d)
            first_prime = b64_to_int(p)
            second_prime = b64_to_int(q)
            first_prime_crt = b64_to_int(dp)
            second_prime_crt = b64_to_int(dq)
            crt_coefficient = b64_to_int(qi)

            if not first_prime or not second_prime:
                first_prime, second_prime = rsa.rsa_recover_prime_factors(
                    modulus, public_exponent, private_exponent)

            if not first_prime_crt:
                first_prime_crt = rsa.rsa_crt_dmp1(private_exponent,
                                                   first_prime)

            if not second_prime_crt:
                second_prime_crt = rsa.rsa_crt_dmq1(private_exponent,
                                                    second_prime)

            if not crt_coefficient:
                crt_coefficient = rsa.rsa_crt_iqmp(first_prime, second_prime)

            private = rsa.RSAPrivateNumbers(
                first_prime,
                second_prime,
                private_exponent,
                first_prime_crt,
                second_prime_crt,
                crt_coefficient,
                public,
            )

            self._private: RSA_PRIVATE = private.private_key(default_backend())
Esempio n. 8
0
    def __init__(self, n, e, d=None, p=None, q=None,
                 dmp1=None, dmq1=None, iqmp=None):
        self._pub = rsa.RSAPublicNumbers(e, n)

        if d:
            self._priv = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1,
                                               iqmp, self._pub)
            self._priv_key = self._priv.private_key(default_backend())
        else:
            self._priv = None
            self._pub_key = self._pub.public_key(default_backend())
Esempio n. 9
0
def make_privkey(p, q, e=65537):
    n = p * q
    d = number.inverse(e, (p - 1) * (q - 1))
    iqmp = rsa.rsa_crt_iqmp(p, q)
    dmp1 = rsa.rsa_crt_dmp1(e, p)
    dmq1 = rsa.rsa_crt_dmq1(e, q)
    pub = rsa.RSAPublicNumbers(e, n)
    priv = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, pub)
    pubkey = pub.public_key(default_backend())
    privkey = priv.private_key(default_backend())
    return privkey, pubkey
Esempio n. 10
0
 def private_numbers(self):
     return rsa.RSAPrivateNumbers(
         p=self._backend._bn_to_int(self._rsa_cdata.p),
         q=self._backend._bn_to_int(self._rsa_cdata.q),
         d=self._backend._bn_to_int(self._rsa_cdata.d),
         dmp1=self._backend._bn_to_int(self._rsa_cdata.dmp1),
         dmq1=self._backend._bn_to_int(self._rsa_cdata.dmq1),
         iqmp=self._backend._bn_to_int(self._rsa_cdata.iqmp),
         public_numbers=rsa.RSAPublicNumbers(
             e=self._backend._bn_to_int(self._rsa_cdata.e),
             n=self._backend._bn_to_int(self._rsa_cdata.n),
         ))
Esempio n. 11
0
 def extract_key(self):
     if self.kty == PbWKType.EC:
         if self.kty_prop_ec.crv == PbWKTypeECCurve.P_256:
             key_size = 256
             x = BitArray(bytes=self.kty_prop_ec.x, length=key_size).uint
             y = BitArray(bytes=self.kty_prop_ec.y, length=key_size).uint
             public_numbers = ec.EllipticCurvePublicNumbers(
                 x, y, ec.SECP256R1())
         elif self.kty_prop_ec.crv == PbWKTypeECCurve.P_384:
             key_size = 384
             x = BitArray(bytes=self.kty_prop_ec.x, length=key_size).uint
             y = BitArray(bytes=self.kty_prop_ec.y, length=key_size).uint
             public_numbers = ec.EllipticCurvePublicNumbers(
                 x, y, ec.SECP384R1())
         elif self.kty_prop_ec.crv == PbWKTypeECCurve.P_521:
             key_size = 521
             x = BitArray(bytes=self.kty_prop_ec.x, length=key_size).uint
             y = BitArray(bytes=self.kty_prop_ec.y, length=key_size).uint
             public_numbers = ec.EllipticCurvePublicNumbers(
                 x, y, ec.SECP521R1())
         # return private_key or public_key
         if self.kty_prop_ec.d:
             d = BitArray(bytes=self.kty_prop_ec.d, length=key_size).uint
             private_numbers = ec.EllipticCurvePrivateNumbers(
                 d, public_numbers)
             key = private_numbers.private_key(default_backend())
         else:
             key = public_numbers.public_key(default_backend())
     elif self.kty == PbWKType.RSA:
         n = BitArray(bytes=self.kty_prop_rsa.n).uint
         e = BitArray(bytes=self.kty_prop_rsa.e).uint
         public_numbers = rsa.RSAPublicNumbers(e, n)
         # return private_key or public_key
         if self.kty_prop_rsa.d:
             d = BitArray(bytes=self.kty_prop_rsa.d).uint
             p = BitArray(bytes=self.kty_prop_rsa.p).uint
             q = BitArray(bytes=self.kty_prop_rsa.q).uint
             dmp1 = BitArray(bytes=self.kty_prop_rsa.dp).uint
             dmq1 = BitArray(bytes=self.kty_prop_rsa.dq).uint
             iqmp = BitArray(bytes=self.kty_prop_rsa.qi).uint
             private_numbers = rsa.RSAPrivateNumbers(
                 p, q, d, dmp1, dmq1, iqmp, public_numbers)
             key = private_numbers.private_key(default_backend())
         else:
             key = public_numbers.public_key(default_backend())
     elif self.kty == PbWKType.OCT:
         key_size = len(self.kty_prop_oct.k) * 8
         assert (key_size % 8 == 0)
         key = BitArray(bytes=self.kty_prop_oct.k, length=key_size).bytes
     else:
         raise TypeError()
     return key
Esempio n. 12
0
    def load_rsa_key():
        with open(os.path.join(BASE_PATH, 'jwk_rsa_key.json'), 'r') as infile:
            keyobj = json.load(infile)

        return rsa.RSAPrivateNumbers(
            p=decode_value(keyobj['p']),
            q=decode_value(keyobj['q']),
            d=decode_value(keyobj['d']),
            dmp1=decode_value(keyobj['dp']),
            dmq1=decode_value(keyobj['dq']),
            iqmp=decode_value(keyobj['qi']),
            public_numbers=load_rsa_pub_key().public_numbers()).private_key(
                default_backend())
Esempio n. 13
0
def rsa_pq(p, q, e=65537):
    n = p * q
    public_numbers = rsa.RSAPublicNumbers(e=e, n=n)
    d = rsa._modinv(e, (p - 1) * (q - 1) // 2)
    private_numbers = rsa.RSAPrivateNumbers(
        public_numbers=public_numbers,
        p=p,
        q=q,
        d=d,
        dmp1=rsa.rsa_crt_dmp1(d, p),
        dmq1=rsa.rsa_crt_dmq1(d, q),
        iqmp=rsa.rsa_crt_iqmp(p, q),
    )
    return private_numbers.private_key(backend)
Esempio n. 14
0
def make_rsa_privkey(material, backend):
    public_material = material['public']
    private_material = material['private']
    n = public_material['n']  # Note: all the number are already int
    e = public_material['e']
    d = private_material['d']
    p = private_material['p']
    q = private_material['q']
    pub = rsa.RSAPublicNumbers(e, n)
    dmp1 = rsa.rsa_crt_dmp1(d, p)
    dmq1 = rsa.rsa_crt_dmq1(d, q)
    iqmp = rsa.rsa_crt_iqmp(p, q)
    return rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                 pub).private_key(backend)
Esempio n. 15
0
    def key_unwrap(cls, key: 'RSA', data: bytes) -> bytes:
        pad = cls.get_pad_func(cls.get_hash_func())

        public_nums = rsa.RSAPublicNumbers(e=int.from_bytes(key.e, 'big'), n=int.from_bytes(key.n, 'big'))
        private_nums = rsa.RSAPrivateNumbers(p=int.from_bytes(key.p, 'big'),
                                             q=int.from_bytes(key.q, 'big'),
                                             d=int.from_bytes(key.d, 'big'),
                                             dmp1=int.from_bytes(key.dp, 'big'),
                                             dmq1=int.from_bytes(key.dq, 'big'),
                                             iqmp=int.from_bytes(key.qinv, 'big'),
                                             public_numbers=public_nums)

        sk = private_nums.private_key(default_backend())

        return sk.decrypt(data, pad)
Esempio n. 16
0
def make_pem_rsa_private_key(fname, n, e, d):
    p, q = rsa_factor_given_private_key(n, e, d)
    dmp1 = d % (p - 1)
    dmq1 = d % (q - 1)
    iqmp = num.mod_inverse(q, p)
    pub_nums = rsa.RSAPublicNumbers(e, n)
    priv_nums = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, pub_nums)
    key = priv_nums.private_key(const.BACKEND)
    pem = key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.TraditionalOpenSSL,
        serialization.NoEncryption()
    )
    with open(fname, 'wb') as f:
        f.write(pem)
Esempio n. 17
0
 def _test_private_jwk(key):
     """
     Attempt to read in the key into a private key object
     """
     keys = json.loads(key.decode())
     public_key_numbers = rsa.RSAPublicNumbers(
         long_from_bytes(keys['keys'][0]['e']),
         long_from_bytes(keys['keys'][0]['n']))
     private_key_numbers = rsa.RSAPrivateNumbers(
         long_from_bytes(keys['keys'][0]['p']),
         long_from_bytes(keys['keys'][0]['q']),
         long_from_bytes(keys['keys'][0]['d']),
         long_from_bytes(keys['keys'][0]['dp']),
         long_from_bytes(keys['keys'][0]['dq']),
         long_from_bytes(keys['keys'][0]['qi']), public_key_numbers)
     return private_key_numbers.private_key(default_backend())
Esempio n. 18
0
def make_rsa_key(material):
    '''Convert a hex-based dict of values to an RSA key'''
    backend = default_backend()
    public_material = material['public']
    private_material = material['private']
    n = int(public_material['n'], 16)
    e = int(public_material['e'], 16)
    d = int(private_material['d'], 16)
    p = int(private_material['p'], 16)
    q = int(private_material['q'], 16)
    pub = rsa.RSAPublicNumbers(e, n)
    dmp1 = rsa.rsa_crt_dmp1(d, p)
    dmq1 = rsa.rsa_crt_dmq1(d, q)
    iqmp = rsa.rsa_crt_iqmp(p, q)
    return rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                 pub).private_key(backend), padding.PKCS1v15()
def main(fn):
    for case in parse(fn):

        if case['SHAAlg'] == 'SHA224':
            # SHA224 not supported in *ring*.
            continue

        # Read private key components.
        n = int(case['n'], 16)
        e = int(case['e'], 16)
        d = int(case['d'], 16)

        # Recover the prime factors and CRT numbers.
        p, q = rsa.rsa_recover_prime_factors(n, e, d)
        # cryptography returns p, q with p < q by default. *ring* requires
        # p > q, so swap them here.
        p, q = max(p, q), min(p, q)
        dmp1 = rsa.rsa_crt_dmp1(d, p)
        dmq1 = rsa.rsa_crt_dmq1(d, q)
        iqmp = rsa.rsa_crt_iqmp(p, q)

        # Create a private key instance.
        pub = rsa.RSAPublicNumbers(e, n)
        priv = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, pub)
        key = priv.private_key(default_backend())

        # Recalculate and compare the signature to validate our processing.
        msg = case['Msg'].decode('hex')
        sig = key.sign(msg, padding.PKCS1v15(),
                       getattr(hashes, case['SHAAlg'])())
        hex_sig = ''.join('{:02x}'.format(ord(c)) for c in sig)
        assert hex_sig == case['S']

        # Serialize the private key in DER format.
        der = key.private_bytes(serialization.Encoding.DER,
                                serialization.PrivateFormat.TraditionalOpenSSL,
                                serialization.NoEncryption())
        hex_der = ''.join('{:02x}'.format(ord(c)) for c in der)

        # Print the test case data in the format used by *ring* test files.
        print 'Digest = %s' % case['SHAAlg']
        print 'Key = %s' % hex_der
        print 'Msg = %s' % case['Msg']
        print 'Sig = %s' % case['S']
        print 'Result = Pass'
        print ''
Esempio n. 20
0
    def sign(cls, key: 'RSA', data: bytes) -> bytes:
        hash_cls = cls.get_hash_func()
        pad = cls.get_pad_func(hash_cls)

        public_nums = rsa.RSAPublicNumbers(e=int.from_bytes(key.e, 'big'),
                                           n=int.from_bytes(key.n, 'big'))
        private_nums = rsa.RSAPrivateNumbers(
            p=int.from_bytes(key.p, 'big'),
            q=int.from_bytes(key.q, 'big'),
            d=int.from_bytes(key.d, 'big'),
            dmp1=int.from_bytes(key.dp, 'big'),
            dmq1=int.from_bytes(key.dq, 'big'),
            iqmp=int.from_bytes(key.qinv, 'big'),
            public_numbers=public_nums)

        sk = private_nums.private_key(backend=default_backend())

        return sk.sign(data, pad, hash_cls())
Esempio n. 21
0
    def load_private(self, data, pubfields, backend):
        """Make RSA private key from data."""
        n, data = _get_mpint(data)
        e, data = _get_mpint(data)
        d, data = _get_mpint(data)
        iqmp, data = _get_mpint(data)
        p, data = _get_mpint(data)
        q, data = _get_mpint(data)

        if (e, n) != pubfields:
            raise ValueError("Corrupt data: rsa field mismatch")
        dmp1 = rsa.rsa_crt_dmp1(d, p)
        dmq1 = rsa.rsa_crt_dmq1(d, q)
        public_numbers = rsa.RSAPublicNumbers(e, n)
        private_numbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                                public_numbers)
        private_key = private_numbers.private_key(backend)
        return private_key, data
Esempio n. 22
0
    def v(self):
        """
        Dump private key in PKCS#1 format.  Use cryptography to do this if
        possible, since that is much more likely to be correct.

        (https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#key-serialization)

        Otherwise, attempt to do it ourselves.

        PKCS#1 format is a DER sequence
        (https://msdn.microsoft.com/en-us/library/windows/desktop/bb648645(v=vs.85).aspx)
        of integers
        (https://msdn.microsoft.com/en-us/library/windows/desktop/bb540806(v=vs.85).aspx)
        """
        if cryptography:
            pn = rsa.RSAPrivateNumbers(p=self.p.dereference().v(),
                                       q=self.q.dereference().v(),
                                       d=self.d_.dereference().v(),
                                       dmp1=self.dmp1.dereference().v(),
                                       dmq1=self.dmq1.dereference().v(),
                                       iqmp=self.iqmp.dereference().v(),
                                       public_numbers=rsa.RSAPublicNumbers(
                                           e=self.e.dereference().v(),
                                           n=self.n.dereference().v()))
            return pn.private_key(backend).private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption())

        order_of_numbers = ('n', 'e', 'd_', 'p', 'q', 'dmp1', 'dmq1', 'iqmp')
        hex_values = ([_hexify(0)] +  # version
                      [
                          _hexify(getattr(self, ptr).dereference().v())
                          for ptr in order_of_numbers
                      ])

        integers = [_der_tlv_triplet(val, '02') for val in hex_values]
        der_sequence = _der_tlv_triplet("".join(integers), '30')

        pem = "\n".join(
            ["-----BEGIN RSA PRIVATE KEY-----"] +
            wrap(b64encode(bytearray.fromhex(der_sequence)), width=64) +
            ["-----END RSA PRIVATE KEY-----", ""])
        return pem
Esempio n. 23
0
    def get_private_key(n, e, d):
        '''
        Get private key object given private key numbers
            @in: key_numbers={'n':n, 'e':e,'d':d,}
            @out: private_key object
        '''
        # reconstruct private key
        p, q = rsa.rsa_recover_prime_factors(n, e, d)
        iqmp = rsa.rsa_crt_iqmp(p, q)
        dmp1 = rsa.rsa_crt_dmp1(d, p)
        dmq1 = rsa.rsa_crt_dmq1(d, q)

        # call RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, public_numbers)
        private_numbers = rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp,
                                                rsa.RSAPublicNumbers(e, n))
        # get private key object
        private_key = private_numbers.private_key(default_backend())

        return private_key
Esempio n. 24
0
    def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'RSA':
            raise JWKError(
                "Incorrect key type.  Expected: 'RSA', Received: %s" %
                jwk_dict.get('kty'))

        e = base64_to_long(jwk_dict.get('e', 256))
        n = base64_to_long(jwk_dict.get('n'))
        public = rsa.RSAPublicNumbers(e, n)

        if 'd' not in jwk_dict:
            return public.public_key(self.cryptography_backend())
        else:
            # This is a private key.
            d = base64_to_long(jwk_dict.get('d'))

            extra_params = ['p', 'q', 'dp', 'dq', 'qi']

            if any(k in jwk_dict for k in extra_params):
                # Precomputed private key parameters are available.
                if not all(k in jwk_dict for k in extra_params):
                    # These values must be present when 'p' is according to
                    # Section 6.3.2 of RFC7518, so if they are not we raise
                    # an error.
                    raise JWKError(
                        'Precomputed private key parameters are incomplete.')

                p = base64_to_long(jwk_dict['p'])
                q = base64_to_long(jwk_dict['q'])
                dp = base64_to_long(jwk_dict['dp'])
                dq = base64_to_long(jwk_dict['dq'])
                qi = base64_to_long(jwk_dict['qi'])
            else:
                # The precomputed private key parameters are not available,
                # so we use cryptography's API to fill them in.
                p, q = rsa.rsa_recover_prime_factors(n, e, d)
                dp = rsa.rsa_crt_dmp1(d, p)
                dq = rsa.rsa_crt_dmq1(d, q)
                qi = rsa.rsa_crt_iqmp(p, q)

            private = rsa.RSAPrivateNumbers(p, q, d, dp, dq, qi, public)

            return private.private_key(self.cryptography_backend())
Esempio n. 25
0
 def updateWith(self, privkey):
     self.modulus = privkey.modulus.val
     self.modulusLen = len(binrepr(privkey.modulus.val))
     self.pubExp = privkey.publicExponent.val
     self.privExp = privkey.privateExponent.val
     self.prime1 = privkey.prime1.val
     self.prime2 = privkey.prime2.val
     self.exponent1 = privkey.exponent1.val
     self.exponent2 = privkey.exponent2.val
     self.coefficient = privkey.coefficient.val
     self.key = rsa.RSAPrivateNumbers(
         p=self.prime1,
         q=self.prime2,
         d=self.privExp,
         dmp1=self.exponent1,
         dmq1=self.exponent2,
         iqmp=self.coefficient,
         public_numbers=rsa.RSAPublicNumbers(n=self.modulus, e=self.pubExp),
     ).private_key(default_backend())
Esempio n. 26
0
    def _fromRSAComponents(cls, n, e, d=None, p=None, q=None, u=None):
        """
        Build a key from RSA numerical components.

        @type n: L{int}
        @param n: The 'n' RSA variable.

        @type e: L{int}
        @param e: The 'e' RSA variable.

        @type d: L{int} or L{None}
        @param d: The 'd' RSA variable (optional for a public key).

        @type p: L{int} or L{None}
        @param p: The 'p' RSA variable (optional for a public key).

        @type q: L{int} or L{None}
        @param q: The 'q' RSA variable (optional for a public key).

        @type u: L{int} or L{None}
        @param u: The 'u' RSA variable. Ignored, as its value is determined by
        p and q.

        @rtype: L{Key}
        @return: An RSA key constructed from the values as given.
        """
        publicNumbers = rsa.RSAPublicNumbers(e=e, n=n)
        if d is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = rsa.RSAPrivateNumbers(
                p=p,
                q=q,
                d=d,
                dmp1=rsa.rsa_crt_dmp1(d, p),
                dmq1=rsa.rsa_crt_dmq1(d, q),
                iqmp=rsa.rsa_crt_iqmp(p, q),
                public_numbers=publicNumbers,
            )
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject)
Esempio n. 27
0
    def fill_and_store(self,
                       modulus=None,
                       modulusLen=None,
                       pubExp=None,
                       prime1=None,
                       prime2=None,
                       coefficient=None,
                       exponent1=None,
                       exponent2=None,
                       privExp=None):
        pubExp = pubExp or 65537
        if None in [
                modulus, prime1, prime2, coefficient, privExp, exponent1,
                exponent2
        ]:
            # note that the library requires every parameter
            # in order to call RSAPrivateNumbers(...)
            # if one of these is missing, we generate a whole new key
            real_modulusLen = modulusLen or 2048
            self.key = rsa.generate_private_key(public_exponent=pubExp,
                                                key_size=real_modulusLen,
                                                backend=default_backend())
            self.pubkey = self.key.public_key()
        else:
            real_modulusLen = len(binrepr(modulus))
            if modulusLen and real_modulusLen != modulusLen:
                warning("modulus and modulusLen do not match!")
            pubNum = rsa.RSAPublicNumbers(n=modulus, e=pubExp)
            privNum = rsa.RSAPrivateNumbers(p=prime1,
                                            q=prime2,
                                            dmp1=exponent1,
                                            dmq1=exponent2,
                                            iqmp=coefficient,
                                            d=privExp,
                                            public_numbers=pubNum)
            self.key = privNum.private_key(default_backend())
            self.pubkey = self.key.public_key()

        # Lines below are only useful for the legacy part of pkcs1.py
        pubNum = self.pubkey.public_numbers()
        self._modulusLen = real_modulusLen
        self._modulus = pubNum.n
        self._pubExp = pubNum.e
Esempio n. 28
0
def create_privete_key(public_key, q):
    n = public_key.public_numbers().n
    e = public_key.public_numbers().e
    p = n // q

    phi = (p - 1) * (q - 1)
    d = egcd(e, phi)
    d = d % phi

    if d < 0:
        d += phi

    iqmp = rsa.rsa_crt_iqmp(p, q)
    dmp1 = rsa.rsa_crt_dmp1(d, p)
    dmq1 = rsa.rsa_crt_dmq1(d, q)

    private_key = rsa.RSAPrivateNumbers(
        p, q, d, dmp1, dmq1, iqmp, public_key.public_numbers()).private_key()
    return private_key
Esempio n. 29
0
    def convert_key(cls, packet, private=False):
        if isinstance(packet, RSAPrivateKey) or isinstance(
                packet, RSAPublicKey) or isinstance(
                    packet, DSAPublicKey) or isinstance(packet, DSAPrivateKey):
            if (not private) and (isinstance(packet, DSAPrivateKey)
                                  or isinstance(packet, RSAPrivateKey)):
                return packet.public_key()
            else:
                return packet

        packet = cls._parse_packet(packet)
        if isinstance(packet, OpenPGP.Message):
            packet = packet[0]

        if packet.key_algorithm_name() == 'DSA':
            params = dsa.DSAParameterNumbers(
                cls._bytes_to_long(packet.key['p']),
                cls._bytes_to_long(packet.key['q']),
                cls._bytes_to_long(packet.key['g']))
            public = dsa.DSAPublicNumbers(cls._bytes_to_long(packet.key['y']),
                                          params)
            if private:
                return dsa.DSAPrivateNumbers(
                    cls._bytes_to_long(packet.key['x']),
                    public).private_key(openssl.backend)
            else:
                return public.public_key(openssl.backend)
        else:  # RSA
            public = rsa.RSAPublicNumbers(cls._bytes_to_long(packet.key['e']),
                                          cls._bytes_to_long(packet.key['n']))
            if private:
                d = cls._bytes_to_long(packet.key['d'])
                p = cls._bytes_to_long(packet.key['q'])
                q = cls._bytes_to_long(packet.key['p'])
                dmp1 = rsa.rsa_crt_dmp1(d, p)
                dmq1 = rsa.rsa_crt_dmp1(d, q)
                u = cls._bytes_to_long(packet.key['u'])
                return rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, u,
                                             public).private_key(
                                                 default_backend())
            else:
                return public.public_key(default_backend())
Esempio n. 30
0
    def oaep_vectors(self, Venc, Vmsg):
        pubnum = rsa.RSAPublicNumbers(n=self.n, e=self.e)
        key = rsa.RSAPrivateNumbers(p=self.p,
                                    q=self.q,
                                    d=self.d,
                                    dmp1=self.dp1,
                                    dmq1=self.dq1,
                                    iqmp=self.qinv,
                                    public_numbers=pubnum).private_key(
                                        default_backend())

        asymkey = AsymmetricKey.put(self.session, 0, 'OAEP Vectors', 0xffff,
                                    CAPABILITY.DECRYPT_OAEP, key)

        dec = asymkey.decrypt_oaep(Venc,
                                   hash=hashes.SHA1(),
                                   mgf_hash=hashes.SHA1())
        self.assertEqual(Vmsg, dec)

        asymkey.delete()