Python cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers() Examples

The following are 17 code examples of cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers(). 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.ec , or try the search function .
Example #1
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def decrypt(self, pk, *args):
        km = pk.keymaterial
        if km.oid == EllipticCurveOID.Curve25519:
            v = x25519.X25519PublicKey.from_public_bytes(self.p.x)
            s = km.__privkey__().exchange(v)
        else:
            # assemble the public component of ephemeral key v
            v = ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, km.oid.curve()).public_key(default_backend())
            # compute s using the inverse of how it was derived during encryption
            s = km.__privkey__().exchange(ec.ECDH(), v)

        # derive the wrapping key
        z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint)

        # unwrap and unpad m
        _m = aes_key_unwrap(z, self.c, default_backend())

        padder = PKCS7(64).unpadder()
        return padder.update(_m) + padder.finalize() 
Example #2
Source File: cryptography_backend.py    From python-jose with MIT License 6 votes vote down vote up
def _process_jwk(self, jwk_dict):
        if not jwk_dict.get('kty') == 'EC':
            raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty'))

        if not all(k in jwk_dict for k in ['x', 'y', 'crv']):
            raise JWKError('Mandatory parameters are missing')

        x = base64_to_long(jwk_dict.get('x'))
        y = base64_to_long(jwk_dict.get('y'))
        curve = {
            'P-256': ec.SECP256R1,
            'P-384': ec.SECP384R1,
            'P-521': ec.SECP521R1,
        }[jwk_dict['crv']]

        public = ec.EllipticCurvePublicNumbers(x, y, curve())

        if 'd' in jwk_dict:
            d = base64_to_long(jwk_dict.get('d'))
            private = ec.EllipticCurvePrivateNumbers(d, public)

            return private.private_key(self.cryptography_backend())
        else:
            return public.public_key(self.cryptography_backend()) 
Example #3
Source File: test_keys.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_fromPrivateBlobECDSA(self):
        """
        A private EC key is correctly generated from a private key blob.
        """
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import ec
        from cryptography.hazmat.primitives import serialization
        publicNumbers = ec.EllipticCurvePublicNumbers(
            x=keydata.ECDatanistp256['x'], y=keydata.ECDatanistp256['y'],
            curve=ec.SECP256R1())
        ecblob = (
            common.NS(keydata.ECDatanistp256['curve']) +
            common.NS(keydata.ECDatanistp256['curve'][-8:]) +
            common.NS(publicNumbers.public_key(default_backend()).public_bytes(
                serialization.Encoding.X962,
                serialization.PublicFormat.UncompressedPoint
            )) +
            common.MP(keydata.ECDatanistp256['privateValue'])
        )

        eckey = keys.Key._fromString_PRIVATE_BLOB(ecblob)

        self.assertFalse(eckey.isPublic())
        self.assertEqual(keydata.ECDatanistp256, eckey.data()) 
Example #4
Source File: jwk.py    From jwcrypto with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _ec_pub(self, k, curve):
        return ec.EllipticCurvePublicNumbers(self._decode_int(k['x']),
                                             self._decode_int(k['y']),
                                             self.get_curve(curve)) 
Example #5
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __privkey__(self):
        ecp = ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, self.oid.curve())
        return ec.EllipticCurvePrivateNumbers(self.s, ecp).private_key(default_backend()) 
Example #6
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __pubkey__(self):
        if self.oid == EllipticCurveOID.Curve25519:
            return x25519.X25519PublicKey.from_public_bytes(self.p.x)
        else:
            return ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, self.oid.curve()).public_key(default_backend()) 
Example #7
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __pubkey__(self):
        return ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, self.oid.curve()).public_key(default_backend()) 
Example #8
Source File: jwtutil.py    From quay with Apache License 2.0 5 votes vote down vote up
def jwk_dict_to_public_key(jwk):
    """
    Converts the specified JWK into a public key.
    """
    jwkest_key = keyrep(jwk)
    if isinstance(jwkest_key, RSAKey):
        pycrypto_key = jwkest_key.key
        return RSAPublicNumbers(e=pycrypto_key.e, n=pycrypto_key.n).public_key(default_backend())
    elif isinstance(jwkest_key, ECKey):
        x, y = jwkest_key.get_key()
        return EllipticCurvePublicNumbers(x, y, jwkest_key.curve).public_key(default_backend())

    raise Exception("Unsupported kind of JWK: %s", str(type(jwkest_key))) 
Example #9
Source File: keys.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _fromECComponents(cls, x, y, curve, privateValue=None):
        """
        Build a key from EC components.

        @param x: The affine x component of the public point used for verifying.
        @type x: L{int}

        @param y: The affine y component of the public point used for verifying.
        @type y: L{int}

        @param curve: NIST name of elliptic curve.
        @type curve: L{bytes}

        @param privateValue: The private value.
        @type privateValue: L{int}
        """

        publicNumbers = ec.EllipticCurvePublicNumbers(
            x=x, y=y, curve=_curveTable[curve])
        if privateValue is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = ec.EllipticCurvePrivateNumbers(
                private_value=privateValue, public_numbers=publicNumbers)
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject) 
Example #10
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _fromECComponents(cls, x, y, curve, privateValue=None):
        """
        Build a key from EC components.

        @param x: The affine x component of the public point used for verifying.
        @type x: L{int}

        @param y: The affine y component of the public point used for verifying.
        @type y: L{int}

        @param curve: NIST name of elliptic curve.
        @type curve: L{bytes}

        @param privateValue: The private value.
        @type privateValue: L{int}
        """

        publicNumbers = ec.EllipticCurvePublicNumbers(
            x=x, y=y, curve=_curveTable[curve])
        if privateValue is None:
            # We have public components.
            keyObject = publicNumbers.public_key(default_backend())
        else:
            privateNumbers = ec.EllipticCurvePrivateNumbers(
                private_value=privateValue, public_numbers=publicNumbers)
            keyObject = privateNumbers.private_key(default_backend())

        return cls(keyObject) 
Example #11
Source File: serialization.py    From oss-ftp with MIT License 5 votes vote down vote up
def _load_ssh_ecdsa_public_key(expected_key_type, decoded_data, backend):
    curve_name, rest = _read_next_string(decoded_data)
    data, rest = _read_next_string(rest)

    if expected_key_type != b"ecdsa-sha2-" + curve_name:
        raise ValueError(
            'Key header and key body contain different key type values.'
        )

    if rest:
        raise ValueError('Key body contains extra bytes.')

    curve = {
        b"nistp256": ec.SECP256R1,
        b"nistp384": ec.SECP384R1,
        b"nistp521": ec.SECP521R1,
    }[curve_name]()

    if six.indexbytes(data, 0) != 4:
        raise NotImplementedError(
            "Compressed elliptic curve points are not supported"
        )

    # key_size is in bits, and sometimes it's not evenly divisible by 8, so we
    # add 7 to round up the number of bytes.
    if len(data) != 1 + 2 * ((curve.key_size + 7) // 8):
        raise ValueError("Malformed key bytes")

    x = utils.int_from_bytes(
        data[1:1 + (curve.key_size + 7) // 8], byteorder='big'
    )
    y = utils.int_from_bytes(
        data[1 + (curve.key_size + 7) // 8:], byteorder='big'
    )
    return ec.EllipticCurvePublicNumbers(x, y, curve).public_key(backend) 
Example #12
Source File: elliptic_curve.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def _ecc_public_numbers_from_compressed_point(curve, compressed_point):
    """Decodes a compressed elliptic curve point
        as described in SEC-1 v2 section 2.3.3
        and returns a PublicNumbers instance
        based on the decoded point.
        http://www.secg.org/sec1-v2.pdf

    :param curve: Elliptic curve type to generate
    :type curve: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve
    :param bytes compressed_point: Encoded compressed elliptic curve point
    :returns: EllipticCurvePublicNumbers instance generated from compressed point and curve
    :rtype: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers
    """
    x, y = _ecc_decode_compressed_point(curve, compressed_point)
    return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve) 
Example #13
Source File: credentials.py    From pywarp with Apache License 2.0 5 votes vote down vote up
def verify(self, signature, signed_data):
        ec_curve = EllipticCurves[self.public_key.ec_id]
        ec_pk_numbers = ec.EllipticCurvePublicNumbers(int.from_bytes(self.public_key.x, byteorder="big"),
                                                      int.from_bytes(self.public_key.y, byteorder="big"),
                                                      ec_curve)
        ec_public_key = ec_pk_numbers.public_key(cryptography.hazmat.backends.default_backend())
        sig_alg = SignatureAlgorithms[self.public_key.algorithm]
        ec_public_key.verify(signature, signed_data, ec.ECDSA(sig_alg())) 
Example #14
Source File: __init__.py    From signxml with Apache License 2.0 4 votes vote down vote up
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, der_encoded_key_value,
                                      signature_alg):
        if der_encoded_key_value is not None:
            key = load_der_public_key(b64decode(der_encoded_key_value.text), backend=default_backend())
        if "ecdsa-" in signature_alg:
            if key_value is not None:
                ec_key_value = self._find(key_value, "ECKeyValue", namespace="dsig11")
                named_curve = self._find(ec_key_value, "NamedCurve", namespace="dsig11")
                public_key = self._find(ec_key_value, "PublicKey", namespace="dsig11")
                key_data = b64decode(public_key.text)[1:]
                x = bytes_to_long(key_data[:len(key_data)//2])
                y = bytes_to_long(key_data[len(key_data)//2:])
                curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
                key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend())
            elif not isinstance(key, ec.EllipticCurvePublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            dss_signature = self._encode_dss_signature(raw_signature, key.key_size)
            key.verify(
                dss_signature,
                data=signed_info_c14n,
                signature_algorithm=ec.ECDSA(
                    self._get_signature_digest_method(signature_alg)
                ),
            )
        elif "dsa-" in signature_alg:
            if key_value is not None:
                dsa_key_value = self._find(key_value, "DSAKeyValue")
                p = self._get_long(dsa_key_value, "P")
                q = self._get_long(dsa_key_value, "Q")
                g = self._get_long(dsa_key_value, "G", require=False)
                y = self._get_long(dsa_key_value, "Y")
                pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
                key = pn.public_key(backend=default_backend())
            elif not isinstance(key, dsa.DSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            # TODO: supply meaningful key_size_bits for signature length assertion
            dss_signature = self._encode_dss_signature(raw_signature, len(raw_signature) * 8 / 2)
            key.verify(dss_signature,
                       data=signed_info_c14n,
                       algorithm=self._get_signature_digest_method(signature_alg))
        elif "rsa-" in signature_alg:
            if key_value is not None:
                rsa_key_value = self._find(key_value, "RSAKeyValue")
                modulus = self._get_long(rsa_key_value, "Modulus")
                exponent = self._get_long(rsa_key_value, "Exponent")
                key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend())
            elif not isinstance(key, rsa.RSAPublicKey):
                raise InvalidInput("DER encoded key value does not match specified signature algorithm")
            key.verify(raw_signature,
                       data=signed_info_c14n,
                       padding=PKCS1v15(),
                       algorithm=self._get_signature_digest_method(signature_alg))
        else:
            raise NotImplementedError() 
Example #15
Source File: keys.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def _fromString_BLOB(cls, blob):
        """
        Return a public key object corresponding to this public key blob.
        The format of a RSA public key blob is::
            string 'ssh-rsa'
            integer e
            integer n

        The format of a DSA public key blob is::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y

        The format of ECDSA-SHA2-* public key blob is::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y

            identifier is the standard NIST curve name.

        @type blob: L{bytes}
        @param blob: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type (the first string) is unknown.
        """
        keyType, rest = common.getNS(blob)
        if keyType == b'ssh-rsa':
            e, n, rest = common.getMP(rest, 2)
            return cls(
                rsa.RSAPublicNumbers(e, n).public_key(default_backend()))
        elif keyType == b'ssh-dss':
            p, q, g, y, rest = common.getMP(rest, 4)
            return cls(
                dsa.DSAPublicNumbers(
                    y=y,
                    parameter_numbers=dsa.DSAParameterNumbers(
                        p=p,
                        q=q,
                        g=g
                    )
                ).public_key(default_backend())
            )
        elif keyType in _curveTable:
            # First we have to make an EllipticCuvePublicNumbers from the
            # provided curve and points,
            # then turn it into a public key object.
            return cls(
                ec.EllipticCurvePublicNumbers.from_encoded_point(
                      _curveTable[keyType],
                       common.getNS(rest, 2)[1]).public_key(default_backend()))
        else:
            raise BadKeyError('unknown blob type: %s' % (keyType,)) 
Example #16
Source File: webauthn.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def _load_cose_public_key(key_bytes):

    cose_public_key = cbor2.loads(key_bytes)

    if COSE_PUBLIC_KEY.ALG not in cose_public_key:
        raise COSEKeyException('Public key missing required algorithm parameter.')

    alg = cose_public_key[COSE_PUBLIC_KEY.ALG]

    if alg == COSE_ALGORITHM.ES256:

        required_keys = {
            COSE_PUBLIC_KEY.ALG,
            COSE_PUBLIC_KEY.X,
            COSE_PUBLIC_KEY.Y
        }

        if not set(cose_public_key.keys()).issuperset(required_keys):
            raise COSEKeyException('Public key must match COSE_Key spec.')

        if len(cose_public_key[COSE_PUBLIC_KEY.X]) != 32:
            raise RegistrationRejectedException('Bad public key.')
        x = int(codecs.encode(cose_public_key[COSE_PUBLIC_KEY.X], 'hex'), 16)

        if len(cose_public_key[COSE_PUBLIC_KEY.Y]) != 32:
            raise RegistrationRejectedException('Bad public key.')
        y = int(codecs.encode(cose_public_key[COSE_PUBLIC_KEY.Y], 'hex'), 16)

        return alg, EllipticCurvePublicNumbers(x, y, SECP256R1()).public_key(backend=default_backend())
    elif alg in (COSE_ALGORITHM.PS256, COSE_ALGORITHM.RS256):

        required_keys = {
            COSE_PUBLIC_KEY.ALG,
            COSE_PUBLIC_KEY.E,
            COSE_PUBLIC_KEY.N
        }

        if not set(cose_public_key.keys()).issuperset(required_keys):
            raise COSEKeyException('Public key must match COSE_Key spec.')

        if len(cose_public_key[COSE_PUBLIC_KEY.E]) != 3 or len(cose_public_key[COSE_PUBLIC_KEY.N]) != 256:
            raise COSEKeyException('Bad public key.')

        e = int(codecs.encode(cose_public_key[COSE_PUBLIC_KEY.E], 'hex'), 16)
        n = int(codecs.encode(cose_public_key[COSE_PUBLIC_KEY.N], 'hex'), 16)

        return alg, RSAPublicNumbers(e, n).public_key(backend=default_backend())
    else:
        raise COSEKeyException('Unsupported algorithm.') 
Example #17
Source File: ecdsa.py    From python-graphenelib with MIT License 4 votes vote down vote up
def recover_public_key(digest, signature, i, message=None):
    """ Recover the public key from the the signature
    """

    # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily
    curve = ecdsa.SECP256k1.curve
    G = ecdsa.SECP256k1.generator
    order = ecdsa.SECP256k1.order
    yp = i % 2
    r, s = ecdsa.util.sigdecode_string(signature, order)
    # 1.1
    x = r + (i // 2) * order
    # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified.
    # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve.
    alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p()
    beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p())
    y = beta if (beta - yp) % 2 == 0 else curve.p() - beta
    # 1.4 Constructor of Point is supposed to check if nR is at infinity.
    R = ecdsa.ellipticcurve.Point(curve, x, y, order)
    # 1.5 Compute e
    e = ecdsa.util.string_to_number(digest)
    # 1.6 Compute Q = r^-1(sR - eG)
    Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G)

    if SECP256K1_MODULE == "cryptography" and message is not None:
        if not isinstance(message, bytes):
            message = bytes(message, "utf-8")  # pragma: no cover
        sigder = encode_dss_signature(r, s)
        public_key = ec.EllipticCurvePublicNumbers(
            Q._Point__x, Q._Point__y, ec.SECP256K1()
        ).public_key(default_backend())
        public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256()))
        return public_key
    else:
        # Not strictly necessary, but let's verify the message for paranoia's sake.
        if not ecdsa.VerifyingKey.from_public_point(
            Q, curve=ecdsa.SECP256k1
        ).verify_digest(
            signature, digest, sigdecode=ecdsa.util.sigdecode_string
        ):  # pragma: no cover
            return None  # pragma: no cover
        return ecdsa.VerifyingKey.from_public_point(
            Q, curve=ecdsa.SECP256k1
        )  # pragma: no cover