Python cryptography.hazmat.primitives.asymmetric.rsa.rsa_crt_iqmp() Examples

The following are 11 code examples of cryptography.hazmat.primitives.asymmetric.rsa.rsa_crt_iqmp(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.hazmat.primitives.asymmetric.rsa , or try the search function .
Example #1
Source File: __init__.py    From lokey with GNU General Public License v3.0 6 votes vote down vote up
def deserialize(self, data):
        pgp_key, _ = pgpy.PGPKey.from_blob(data)
        password = ""
        if self.password:
            password = self.password
        with pgp_key.unlock(password):
            key_material = pgp_key._key.keymaterial
            # https://tools.ietf.org/html/rfc4880#section-5.5.3
            # "multiprecision integer (MPI) of RSA secret exponent d."
            self._d = key_material.d
            # "MPI of RSA secret prime value p."
            self._p = key_material.p
            # "MPI of RSA secret prime value q (p < q)."
            self._q = key_material.q
            self._iqmp = rsa.rsa_crt_iqmp(key_material.p, key_material.q)
            self._dmp1 = rsa.rsa_crt_dmp1(key_material.d, key_material.q)
            self._dmq1 = rsa.rsa_crt_dmq1(key_material.d, key_material.q)
            self._public_numbers = ErisPublic(
                e=key_material.e,
                n=key_material.n) 
Example #2
Source File: test_keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_privateBlobRSA(self):
        """
        L{keys.Key.privateBlob} returns the SSH protocol-level format of an
        RSA private key.
        """
        from cryptography.hazmat.primitives.asymmetric import rsa
        numbers = self.rsaObj.private_numbers()
        u = rsa.rsa_crt_iqmp(numbers.q, numbers.p)
        self.assertEqual(
            keys.Key(self.rsaObj).privateBlob(),
            common.NS(b'ssh-rsa') +
            common.MP(self.rsaObj.private_numbers().public_numbers.n) +
            common.MP(self.rsaObj.private_numbers().public_numbers.e) +
            common.MP(self.rsaObj.private_numbers().d) +
            common.MP(u) +
            common.MP(self.rsaObj.private_numbers().p) +
            common.MP(self.rsaObj.private_numbers().q)
            ) 
Example #3
Source File: test_keys.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_privateBlobRSA(self):
        """
        L{keys.Key.privateBlob} returns the SSH protocol-level format of an
        RSA private key.
        """
        from cryptography.hazmat.primitives.asymmetric import rsa
        numbers = self.rsaObj.private_numbers()
        u = rsa.rsa_crt_iqmp(numbers.q, numbers.p)
        self.assertEqual(
            keys.Key(self.rsaObj).privateBlob(),
            common.NS(b'ssh-rsa') +
            common.MP(self.rsaObj.private_numbers().public_numbers.n) +
            common.MP(self.rsaObj.private_numbers().public_numbers.e) +
            common.MP(self.rsaObj.private_numbers().d) +
            common.MP(u) +
            common.MP(self.rsaObj.private_numbers().p) +
            common.MP(self.rsaObj.private_numbers().q)
            ) 
Example #4
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _generate(self, key_size):
        if any(c != 0 for c in self):  # pragma: no cover
            raise PGPError("key is already populated")

        # generate some big numbers!
        pk = rsa.generate_private_key(65537, key_size, default_backend())
        pkn = pk.private_numbers()

        self.n = MPI(pkn.public_numbers.n)
        self.e = MPI(pkn.public_numbers.e)
        self.d = MPI(pkn.d)
        self.p = MPI(pkn.p)
        self.q = MPI(pkn.q)
        # from the RFC:
        # "- MPI of u, the multiplicative inverse of p, mod q."
        # or, simply, p^-1 mod p
        # rsa.rsa_crt_iqmp(p, q) normally computes q^-1 mod p,
        # so if we swap the values around we get the answer we want
        self.u = MPI(rsa.rsa_crt_iqmp(pkn.q, pkn.p))

        del pkn
        del pk

        self._compute_chksum() 
Example #5
Source File: cryptography_backend.py    From python-jose with MIT License 5 votes vote down vote up
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()) 
Example #6
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __privkey__(self):
        return rsa.RSAPrivateNumbers(self.p, self.q, self.d,
                                     rsa.rsa_crt_dmp1(self.d, self.p),
                                     rsa.rsa_crt_dmq1(self.d, self.q),
                                     rsa.rsa_crt_iqmp(self.p, self.q),
                                     rsa.RSAPublicNumbers(self.e, self.n)).private_key(default_backend()) 
Example #7
Source File: __init__.py    From lokey with GNU General Public License v3.0 4 votes vote down vote up
def serialize(self, name, comment, email):
        rsa_priv = RSAPriv()
        rsa_priv.e = MPI(self.public_numbers._e)
        rsa_priv.n = MPI(self.public_numbers._n)
        rsa_priv.d = MPI(self._d)
        rsa_priv.p = MPI(self._p)
        rsa_priv.q = MPI(self._q)
        # https://github.com/SecurityInnovation/PGPy/blob/f08afed730816e71eafa0dd59ce77d8859ce24b5/pgpy/packet/fields.py#L1116
        rsa_priv.u = MPI(rsa.rsa_crt_iqmp(self._q, self._p))
        rsa_priv._compute_chksum()

        pub_key_v4 = PrivKeyV4()
        pub_key_v4.pkalg = PubKeyAlgorithm.RSAEncryptOrSign
        pub_key_v4.keymaterial = rsa_priv
        pub_key_v4.update_hlen()

        pgp_key = pgpy.PGPKey()
        pgp_key._key = pub_key_v4

        uid = pgpy.PGPUID.new(name, comment=comment, email=email)

        # FIXME: Should I add a "Signature" Packet?
        # FIXME: Should I add subkeys?

        pgp_key.add_uid(
            uid,
            usage={
                KeyFlags.Sign,
                KeyFlags.EncryptCommunications,
                KeyFlags.EncryptStorage},
            hashes=[
                HashAlgorithm.SHA256,
                HashAlgorithm.SHA384,
                HashAlgorithm.SHA512,
                HashAlgorithm.SHA224],
            ciphers=[
                SymmetricKeyAlgorithm.AES256,
                SymmetricKeyAlgorithm.AES192,
                SymmetricKeyAlgorithm.AES128],
            compression=[
                CompressionAlgorithm.ZLIB,
                CompressionAlgorithm.BZ2,
                CompressionAlgorithm.ZIP,
                CompressionAlgorithm.Uncompressed])

        if self.password:
            pgp_key.protect(
                self.password,
                SymmetricKeyAlgorithm.AES256,
                HashAlgorithm.SHA256)

        return str(pgp_key) 
Example #8
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #9
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def data(self):
        """
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        """
        if isinstance(self._keyObject, rsa.RSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "n": numbers.n,
                "e": numbers.e,
            }
        elif isinstance(self._keyObject, rsa.RSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "n": numbers.public_numbers.n,
                "e": numbers.public_numbers.e,
                "d": numbers.d,
                "p": numbers.p,
                "q": numbers.q,
                # Use a trick: iqmp is q^-1 % p, u is p^-1 % q
                "u": rsa.rsa_crt_iqmp(numbers.q, numbers.p),
            }
        elif isinstance(self._keyObject, dsa.DSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "y": numbers.y,
                "g": numbers.parameter_numbers.g,
                "p": numbers.parameter_numbers.p,
                "q": numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, dsa.DSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.x,
                "y": numbers.public_numbers.y,
                "g": numbers.public_numbers.parameter_numbers.g,
                "p": numbers.public_numbers.parameter_numbers.p,
                "q": numbers.public_numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "x": numbers.x,
                "y": numbers.y,
                "curve": self.sshType(),
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.public_numbers.x,
                "y": numbers.public_numbers.y,
                "privateValue": numbers.private_value,
                "curve": self.sshType(),
            }

        else:
            raise RuntimeError("Unexpected key type: %s" % (self._keyObject,)) 
Example #10
Source File: keys.py    From learn_python3_spider with MIT License 4 votes vote down vote up
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) 
Example #11
Source File: keys.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def data(self):
        """
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        """
        if isinstance(self._keyObject, rsa.RSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "n": numbers.n,
                "e": numbers.e,
            }
        elif isinstance(self._keyObject, rsa.RSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "n": numbers.public_numbers.n,
                "e": numbers.public_numbers.e,
                "d": numbers.d,
                "p": numbers.p,
                "q": numbers.q,
                # Use a trick: iqmp is q^-1 % p, u is p^-1 % q
                "u": rsa.rsa_crt_iqmp(numbers.q, numbers.p),
            }
        elif isinstance(self._keyObject, dsa.DSAPublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "y": numbers.y,
                "g": numbers.parameter_numbers.g,
                "p": numbers.parameter_numbers.p,
                "q": numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, dsa.DSAPrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.x,
                "y": numbers.public_numbers.y,
                "g": numbers.public_numbers.parameter_numbers.g,
                "p": numbers.public_numbers.parameter_numbers.p,
                "q": numbers.public_numbers.parameter_numbers.q,
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePublicKey):
            numbers = self._keyObject.public_numbers()
            return {
                "x": numbers.x,
                "y": numbers.y,
                "curve": self.sshType(),
            }
        elif isinstance(self._keyObject, ec.EllipticCurvePrivateKey):
            numbers = self._keyObject.private_numbers()
            return {
                "x": numbers.public_numbers.x,
                "y": numbers.public_numbers.y,
                "privateValue": numbers.private_value,
                "curve": self.sshType(),
            }

        else:
            raise RuntimeError("Unexpected key type: %s" % (self._keyObject,))