当前位置: 首页>>代码示例>>Python>>正文


Python ec.EllipticCurvePublicNumbers方法代码示例

本文整理汇总了Python中cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers方法的典型用法代码示例。如果您正苦于以下问题:Python ec.EllipticCurvePublicNumbers方法的具体用法?Python ec.EllipticCurvePublicNumbers怎么用?Python ec.EllipticCurvePublicNumbers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cryptography.hazmat.primitives.asymmetric.ec的用法示例。


在下文中一共展示了ec.EllipticCurvePublicNumbers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_fromPrivateBlobECDSA

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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()) 
开发者ID:wistbean,项目名称:learn_python3_spider,代码行数:26,代码来源:test_keys.py

示例2: _process_jwk

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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()) 
开发者ID:mpdavis,项目名称:python-jose,代码行数:26,代码来源:cryptography_backend.py

示例3: decrypt

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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() 
开发者ID:SecurityInnovation,项目名称:PGPy,代码行数:21,代码来源:fields.py

示例4: verify

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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())) 
开发者ID:pyauth,项目名称:pywarp,代码行数:10,代码来源:credentials.py

示例5: _ec_pub

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
def _ec_pub(self, k, curve):
        return ec.EllipticCurvePublicNumbers(self._decode_int(k['x']),
                                             self._decode_int(k['y']),
                                             self.get_curve(curve)) 
开发者ID:latchset,项目名称:jwcrypto,代码行数:6,代码来源:jwk.py

示例6: _ecc_public_numbers_from_compressed_point

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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) 
开发者ID:aws,项目名称:aws-encryption-sdk-python,代码行数:17,代码来源:elliptic_curve.py

示例7: _load_ssh_ecdsa_public_key

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:37,代码来源:serialization.py

示例8: _fromECComponents

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:30,代码来源:keys.py

示例9: jwk_dict_to_public_key

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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))) 
开发者ID:quay,项目名称:quay,代码行数:15,代码来源:jwtutil.py

示例10: __pubkey__

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
def __pubkey__(self):
        return ec.EllipticCurvePublicNumbers(self.p.x, self.p.y, self.oid.curve()).public_key(default_backend()) 
开发者ID:SecurityInnovation,项目名称:PGPy,代码行数:4,代码来源:fields.py

示例11: __privkey__

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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()) 
开发者ID:SecurityInnovation,项目名称:PGPy,代码行数:5,代码来源:fields.py

示例12: _load_cose_public_key

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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.') 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:51,代码来源:webauthn.py

示例13: _fromString_BLOB

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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,)) 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:58,代码来源:keys.py

示例14: _verify_signature_with_pubkey

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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() 
开发者ID:XML-Security,项目名称:signxml,代码行数:56,代码来源:__init__.py

示例15: recover_public_key

# 需要导入模块: from cryptography.hazmat.primitives.asymmetric import ec [as 别名]
# 或者: from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers [as 别名]
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 
开发者ID:xeroc,项目名称:python-graphenelib,代码行数:46,代码来源:ecdsa.py


注:本文中的cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。