Python cryptography.hazmat.primitives.asymmetric.rsa 模块,RSAPublicKey() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey()

项目:newsreap    作者:caronc    | 项目源码 | 文件源码
def public_pem(self):
        """
        Returns the public key PEM. This is a base64 format with delimiters.

        This function returns None if the public pem information could
        not be acquired.

        """
        if not isinstance(self.public_key, RSAPublicKey):
            if not isinstance(self.private_key, RSAPrivateKey):
                return None
            self.public_key = self.private_key.public_key()

        return self.public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo,
        )
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def fields_to_partial_json(self):
        # pylint: disable=protected-access
        if isinstance(self.key._wrapped, rsa.RSAPublicKey):
            numbers = self.key.public_numbers()
            params = {
                'n': numbers.n,
                'e': numbers.e,
            }
        else:  # rsa.RSAPrivateKey
            private = self.key.private_numbers()
            public = self.key.public_key().public_numbers()
            params = {
                'n': public.n,
                'e': public.e,
                'd': private.d,
                'p': private.p,
                'q': private.q,
                'dp': private.dmp1,
                'dq': private.dmq1,
                'qi': private.iqmp,
            }
        return dict((key, self._encode_param(value))
                    for key, value in six.iteritems(params))
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey
项目:cursive    作者:openstack    | 项目源码 | 文件源码
def get_public_key(context, signature_certificate_uuid, signature_key_type):
    """Create the public key object from a retrieved certificate.

    :param context: the user context for authentication
    :param signature_certificate_uuid: the uuid to use to retrieve the
                                       certificate
    :param signature_key_type: a SignatureKeyType object
    :returns: the public key cryptography object
    :raises: SignatureVerificationError if public key format is invalid
    """
    certificate = get_certificate(context, signature_certificate_uuid)

    # Note that this public key could either be
    # RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey
    public_key = certificate.public_key()

    # Confirm the type is of the type expected based on the signature key type
    if not isinstance(public_key, signature_key_type.public_key_type):
        raise exception.SignatureVerificationError(
            reason=_('Invalid public key type for signature key type: %s')
            % signature_key_type.name)

    return public_key
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def from_cryptography_key(cls, crypto_key):
        """
        Construct based on a ``cryptography`` *crypto_key*.

        :param crypto_key: A ``cryptography`` key.
        :type crypto_key: One of ``cryptography``'s `key interfaces`_.

        :rtype: PKey

        .. versionadded:: 16.1.0
        """
        pkey = cls()
        if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                       dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            raise TypeError("Unsupported key type")

        pkey._pkey = crypto_key._evp_pkey
        if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)):
            pkey._only_public = True
        pkey._initialized = True
        return pkey
项目:keyview    作者:ALSchwalm    | 项目源码 | 文件源码
def display_item_info(item, filename, print_filename=False):
    if print_filename is True:
        print("#######[ {} ]#######".format(filename))

    if (isinstance(item, rsa.RSAPrivateKey) or
        isinstance(item, dsa.DSAPrivateKey) or
        isinstance(item, ec.EllipticCurvePrivateKey)):
        display_private_key(item)

    elif (isinstance(item, rsa.RSAPublicKey) or
          isinstance(item, dsa.DSAPublicKey) or
          isinstance(item, ec.EllipticCurvePublicKey)):
        display_public_key(item)

    elif isinstance(item, OpenSSL.crypto.PKCS12):
        display_pkcs12(item)

    elif isinstance(item, OpenSSL.crypto.PKCS7):
        display_pkcs7(item)

    elif isinstance(item, Certificate):
        display_x509_cert(item)
项目:certbot    作者:nikoloskii    | 项目源码 | 文件源码
def fields_to_partial_json(self):
        # pylint: disable=protected-access
        if isinstance(self.key._wrapped, rsa.RSAPublicKey):
            numbers = self.key.public_numbers()
            params = {
                'n': numbers.n,
                'e': numbers.e,
            }
        else:  # rsa.RSAPrivateKey
            private = self.key.private_numbers()
            public = self.key.public_key().public_numbers()
            params = {
                'n': public.n,
                'e': public.e,
                'd': private.d,
                'p': private.p,
                'q': private.q,
                'dp': private.dmp1,
                'dq': private.dmq1,
                'qi': private.iqmp,
            }
        return dict((key, self._encode_param(value))
                    for key, value in six.iteritems(params))
项目:certproxy    作者:geneanet    | 项目源码 | 文件源码
def rsa_key_fingerprint(key):
    """ Return the SHA256 fingerprint of an RSA public or private key in url safe BASE64 """
    fp = hashes.Hash(algorithm=hashes.SHA256(), backend=default_backend())

    if isinstance(key, rsa.RSAPrivateKey):
        fp.update(key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ))
    elif isinstance(key, rsa.RSAPublicKey):
        fp.update(key.public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.PKCS1
        ))

    return urlsafe_b64encode(fp.finalize()).decode()
项目:certproxy    作者:geneanet    | 项目源码 | 文件源码
def dump_pem(key_or_crt):
    if isinstance(key_or_crt, rsa.RSAPrivateKey):
        return key_or_crt.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )
    elif isinstance(key_or_crt, rsa.RSAPublicKey):
        return key_or_crt.public_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PublicFormat.PKCS1
        )
    else:
        return key_or_crt.public_bytes(
            encoding=serialization.Encoding.PEM
        )
项目:delta-sdk-python    作者:Covata    | 项目源码 | 文件源码
def encrypt_key_with_public_key(secret_key, public_encryption_key):
    """
    Encrypts the given secret key with the public key.

    :param bytes secret_key: the key to encrypt
    :param public_encryption_key: the public encryption key
    :type public_encryption_key: :class:`~rsa.RSAPublicKey`
    :return: the encrypted key
    :rtype: bytes
    """
    return public_encryption_key.encrypt(
        secret_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=None))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def type(self):
        """
        Return the type of the object we wrap.  Currently this can only be
        'RSA', 'DSA', or 'EC'.

        @rtype: L{str}
        @raises RuntimeError: If the object type is unknown.
        """
        if isinstance(
                self._keyObject, (rsa.RSAPublicKey, rsa.RSAPrivateKey)):
            return 'RSA'
        elif isinstance(
                self._keyObject, (dsa.DSAPublicKey, dsa.DSAPrivateKey)):
            return 'DSA'
        elif isinstance(
                self._keyObject, (ec.EllipticCurvePublicKey, ec.EllipticCurvePrivateKey)):
            return 'EC'
        else:
            raise RuntimeError(
                'unknown type of object: %r' % (self._keyObject,))
项目:RemoteTree    作者:deNULL    | 项目源码 | 文件源码
def _key_identifier_from_public_key(public_key):
    if isinstance(public_key, RSAPublicKey):
        data = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.PKCS1,
        )
    elif isinstance(public_key, EllipticCurvePublicKey):
        data = public_key.public_numbers().encode_point()
    else:
        # This is a very slow way to do this.
        serialized = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo
        )

        data = six.binary_type(PublicKeyInfo.load(serialized)['public_key'])

    return hashlib.sha1(data).digest()
项目:quickstart-git2s3    作者:aws-quickstart    | 项目源码 | 文件源码
def _key_identifier_from_public_key(public_key):
    if isinstance(public_key, RSAPublicKey):
        data = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.PKCS1,
        )
    elif isinstance(public_key, EllipticCurvePublicKey):
        data = public_key.public_numbers().encode_point()
    else:
        # This is a very slow way to do this.
        serialized = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo
        )

        data = six.binary_type(PublicKeyInfo.load(serialized)['public_key'])

    return hashlib.sha1(data).digest()
项目:ctutlz    作者:theno    | 项目源码 | 文件源码
def pkey_from_cryptography_key(crypto_key):
    '''
    Modified version of `OpenSSL.crypto.PKey.from_cryptography_key()` of
    PyOpenSSL which also accepts EC Keys
    (cf. https://github.com/pyca/pyopenssl/pull/636).
    '''
    pkey = PKey()
    if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey,
                                   dsa.DSAPublicKey, dsa.DSAPrivateKey,
                                   ec.EllipticCurvePublicKey,
                                   ec.EllipticCurvePrivateKey)):
        raise TypeError("Unsupported key type")

    pkey._pkey = crypto_key._evp_pkey
    if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey,
                               ec.EllipticCurvePublicKey)):
        pkey._only_public = True
    pkey._initialized = True
    return pkey
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def get_public_key(context, signature_certificate_uuid, signature_key_type):
    """Create the public key object from a retrieved certificate.

    :param context: the user context for authentication
    :param signature_certificate_uuid: the uuid to use to retrieve the
                                       certificate
    :param signature_key_type: a SignatureKeyType object
    :returns: the public key cryptography object
    :raises: SignatureVerificationError if public key format is invalid
    """
    certificate = get_certificate(context, signature_certificate_uuid)

    # Note that this public key could either be
    # RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey
    public_key = certificate.public_key()

    # Confirm the type is of the type expected based on the signature key type
    if not isinstance(public_key, signature_key_type.public_key_type):
        raise exception.SignatureVerificationError(
            reason=_('Invalid public key type for signature key type: %s')
            % signature_key_type.name)

    return public_key
项目:concorde    作者:frutiger    | 项目源码 | 文件源码
def pubkey_to_jwk(pubkey):
    if isinstance(pubkey, bytes):
        return {
            'kty': 'oct',
            'k': bytes_to_jwk(pubkey),
        }

    if isinstance(pubkey, ec.EllipticCurvePublicKey):
        numbers = pubkey.public_numbers()
        return {
            'kty': 'EC',
            'crv': curve_to_jwk(pubkey.curve.name),
            'x':   uint_to_jwk(numbers.x),
            'y':   uint_to_jwk(numbers.y),
        }

    if isinstance(pubkey, rsa.RSAPublicKey):
        numbers = pubkey.public_numbers()
        return {
            'kty': 'RSA',
            'n':   uint_to_jwk(numbers.n),
            'e':   uint_to_jwk(numbers.e),
        }

    raise ValueError('Unsupported public key: ' + str(type(pubkey)))
项目:newsreap    作者:caronc    | 项目源码 | 文件源码
def genkeys(self, key_size=KeySize.NORMAL, password=None):
        """
        Generates a Private and Public Key set and returns them in a tuple
        (private, public)

        """

        self.private_key = rsa.generate_private_key(
            # The public exponent of the new key. Usually one of the small
            # Fermat primes 3, 5, 17, 257, 65537. If in doubt you should use
            # 65537. See http://www.daemonology.net/blog/2009-06-11-\
            #  cryptographic-right-answers.html
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend()
        )

        # Generate our Public Key
        self.public_key = self.private_key.public_key()

        # Store our password; this will be used when we save our content
        # via it's searialized value later on
        self.password = password

        # Returns a (RSAPrivateKey, RSAPublicKey)
        return (self.private_key, self.public_key)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def _openssh_public_key_bytes(self, key):
        if isinstance(key, rsa.RSAPublicKey):
            public_numbers = key.public_numbers()
            return b"ssh-rsa " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-rsa") +
                serialization._ssh_write_mpint(public_numbers.e) +
                serialization._ssh_write_mpint(public_numbers.n)
            )
        elif isinstance(key, dsa.DSAPublicKey):
            public_numbers = key.public_numbers()
            parameter_numbers = public_numbers.parameter_numbers
            return b"ssh-dss " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-dss") +
                serialization._ssh_write_mpint(parameter_numbers.p) +
                serialization._ssh_write_mpint(parameter_numbers.q) +
                serialization._ssh_write_mpint(parameter_numbers.g) +
                serialization._ssh_write_mpint(public_numbers.y)
            )
        else:
            assert isinstance(key, ec.EllipticCurvePublicKey)
            public_numbers = key.public_numbers()
            try:
                curve_name = {
                    ec.SECP256R1: b"nistp256",
                    ec.SECP384R1: b"nistp384",
                    ec.SECP521R1: b"nistp521",
                }[type(public_numbers.curve)]
            except KeyError:
                raise ValueError(
                    "Only SECP256R1, SECP384R1, and SECP521R1 curves are "
                    "supported by the SSH public key format"
                )
            return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode(
                serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) +
                serialization._ssh_write_string(curve_name) +
                serialization._ssh_write_string(public_numbers.encode_point())
            )
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def calculate_max_pss_salt_length(key, hash_algorithm):
    if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
        raise TypeError("key must be an RSA public or private key")
    # bit length - 1 per RFC 3447
    emlen = int(math.ceil((key.key_size - 1) / 8.0))
    salt_length = emlen - hash_algorithm.digest_size - 2
    assert salt_length >= 0
    return salt_length
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def _key_identifier_from_public_key(public_key):
    if isinstance(public_key, RSAPublicKey):
        data = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.PKCS1,
        )
    elif isinstance(public_key, EllipticCurvePublicKey):
        data = public_key.public_numbers().encode_point()
    else:
        # This is a very slow way to do this.
        serialized = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo
        )
        spki, remaining = decoder.decode(
            serialized, asn1Spec=_SubjectPublicKeyInfo()
        )
        assert not remaining
        # the univ.BitString object is a tuple of bits. We need bytes and
        # pyasn1 really doesn't want to give them to us. To get it we'll
        # build an integer and convert that to bytes.
        bits = 0
        for bit in spki.getComponentByName("subjectPublicKey"):
            bits = bits << 1 | bit

        data = utils.int_to_bytes(bits)

    return hashlib.sha1(data).digest()
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:cursive    作者:openstack    | 项目源码 | 文件源码
def verify_certificate_signature(signing_certificate, certificate):
    """Verify that the certificate was signed correctly.

    :param signing_certificate: the cryptography certificate object used to
           sign the certificate
    :param certificate: the cryptography certificate object that was signed
           by the signing certificate
    :raises: cryptography.exceptions.InvalidSignature if certificate signature
             verification fails.
    """
    signature_hash_algorithm = certificate.signature_hash_algorithm
    signature_bytes = certificate.signature
    signer_public_key = signing_certificate.public_key()

    if isinstance(signer_public_key, rsa.RSAPublicKey):
        verifier = signer_public_key.verifier(
            signature_bytes, padding.PKCS1v15(), signature_hash_algorithm
        )
    elif isinstance(signer_public_key, ec.EllipticCurvePublicKey):
        verifier = signer_public_key.verifier(
            signature_bytes, ec.ECDSA(signature_hash_algorithm)
        )
    else:
        verifier = signer_public_key.verifier(
            signature_bytes, signature_hash_algorithm
        )

    verifier.update(certificate.tbs_certificate_bytes)
    verifier.verify()
项目:cursive    作者:openstack    | 项目源码 | 文件源码
def register(cls, name, public_key_type, create_verifier):
        """Register a signature key type.

        :param name: the name of the signature key type
        :param public_key_type: e.g. RSAPublicKey, DSAPublicKey, etc.
        :param create_verifier: a function to create a verifier for this type
        """
        cls.REGISTERED_TYPES[name] = cls(name,
                                         public_key_type,
                                         create_verifier)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:exe    作者:malice-plugins    | 项目源码 | 文件源码
def _ValidatePubkeyGeneric(self, signing_cert, digest_alg, payload,
                             enc_digest):
    cert = x509.load_der_x509_certificate(der_encoder.encode(signing_cert), default_backend())
    pubkey = cert.public_key()
    if isinstance(pubkey, RSAPublicKey):
        verifier = pubkey.verifier(enc_digest, padding.PKCS1v15(), cert.signature_hash_algorithm)
    else:
        verifier = pubkey.verifier(enc_digest, cert.signature_hash_algorithm)
    verifier.update(payload)
    try:
        verifier.verify()
        return True
    except:
        return False
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def test_convert_public_pkey_to_cryptography_key(self):
        """
        PKey.to_cryptography_key creates a proper cryptography public key.
        """
        pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
        key = pkey.to_cryptography_key()

        assert isinstance(key, rsa.RSAPublicKey)
        assert pkey.bits() == key.key_size
项目:keyview    作者:ALSchwalm    | 项目源码 | 文件源码
def display_public_key(pubkey, indent=""):
    if isinstance(pubkey, rsa.RSAPublicKey):
        display_rsa_public_key(pubkey, indent=indent)
    elif isinstance(pubkey, dsa.DSAPublicKey):
        display_dsa_public_key(pubkey, indent=indent)
    elif isinstance(pubkey, ec.EllipticCurvePublicKey):
        display_ec_public_key(pubkey, indent=indent)
    else:
        raise ValueError("Unknown public key type")
项目:keyview    作者:ALSchwalm    | 项目源码 | 文件源码
def get_public_key_label(pubkey):
    if isinstance(pubkey, rsa.RSAPublicKey):
        return "RSA Public Key"
    elif isinstance(pubkey, dsa.DSAPublicKey):
        return "DSA Public Key"
    elif isinstance(pubkey, ec.EllipticCurvePublicKey):
        return "Elliptic Curve Public Key"
    return None

# From http://matthiaseisen.com/articles/graphviz/
项目:OneClickDTU    作者:satwikkansal    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def verifyCert(cert, signCert):
    """
    Verifies that a certificate has been signed with another. Note that this
    function only verifies the cryptographic signature and is probably wrong and
    dangerous. Do not use it to verify certificates. This function only supports
    ECDSA and RSA+PKCS1 signatures, all other signature types will fail.
    :param cert: The certificate whose signature we want to verify as a
    cryptography certificate object.
    :param signCert: The certificate that was used to sign the first certificate
    as a cryptography certificate object.
    :return: True if the signature is a valid ECDSA signature, False otherwise.
    """
    # FIXME: This is very likely wrong and we should find a better way to verify certs.
    halg = cert.signature_hash_algorithm
    sig = cert.signature
    data = cert.tbs_certificate_bytes

    pubKey = signCert.public_key()
    alg = None
    # We only support ECDSA and RSA+PKCS1
    if isinstance(pubKey, ec.EllipticCurvePublicKey):
        alg = ec.ECDSA(halg)
        ver = pubKey.verifier(sig, alg)
    elif isinstance(pubKey, rsa.RSAPublicKey):
        pad = padding.PKCS1v15()
        ver = pubKey.verifier(sig, pad, halg)
    else:
        return False

    ver.update(data)

    try:
        ver.verify()
        return True
    except InvalidSignature as e:
        return False
项目:mflod    作者:arachnid42    | 项目源码 | 文件源码
def __encrypt_with_rsa(self, content, recipient_pk):
        """ Encrypt content with RSAES-OAEP scheme

        @developer: vsmysle

        This method handles an encryption of a *single* RSA block with a
        specified above scheme. It does not handle splitting of a header into
        several blocks. It has to be done by other method that would use this
        one only for single block encryption purpose.

        TODO: what is a maximum size of a content that can be padded and
        encrypted given a particular size of RSA key?

        :param content:         bytes content to encrypt (probably a part of
                                ASN.1 DER-encoded MPHeader block)
        :param recipient_pk:    instance of cryptography.hazmat.primitives.rsa
                                .RSAPublicKey to use for a content encryption

        :return: string encryption of an input content

        """

        # TODO: add exceptions
        self.logger.debug("rsa encryption")

        ciphertext = recipient_pk.encrypt(
            content, asym_padding.OAEP(
                mgf=asym_padding.MGF1(algorithm=SHA1()),
                algorithm=SHA1(),
                label=None
            )
        )
        self.logger.info("encrypted")
        return ciphertext
项目:mflod    作者:arachnid42    | 项目源码 | 文件源码
def __verify_signature(self, signature, signer_pk, content):
        """ Verify RSASSA-PSS signature

        @developer: vsmysle

        :param signature: signature bytes to verify
        :param signer_pk: instance of cryptography.hazmat.primitives.
                          rsa.RSAPublicKey that is a public key of a signer
        :param content:   content to verify a signature of

        :return: bool verification result

        """
        self.logger.debug("starting signature verification routine")
        try:
            signer_pk.verify(
                signature,
                content,
                asym_padding.PSS(
                    mgf=asym_padding.MGF1(SHA1()),
                    salt_length=asym_padding.PSS.MAX_LENGTH
                ),
                SHA1()
            )
        except InvalidSignature:
            self.logger.warn("signature verification failed")
            return False
        self.logger.info("signature OK")
        return True
项目:slack_scholar    作者:xLeitix    | 项目源码 | 文件源码
def _openssh_public_key_bytes(self, key):
        if isinstance(key, rsa.RSAPublicKey):
            public_numbers = key.public_numbers()
            return b"ssh-rsa " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-rsa") +
                serialization._ssh_write_mpint(public_numbers.e) +
                serialization._ssh_write_mpint(public_numbers.n)
            )
        elif isinstance(key, dsa.DSAPublicKey):
            public_numbers = key.public_numbers()
            parameter_numbers = public_numbers.parameter_numbers
            return b"ssh-dss " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-dss") +
                serialization._ssh_write_mpint(parameter_numbers.p) +
                serialization._ssh_write_mpint(parameter_numbers.q) +
                serialization._ssh_write_mpint(parameter_numbers.g) +
                serialization._ssh_write_mpint(public_numbers.y)
            )
        else:
            assert isinstance(key, ec.EllipticCurvePublicKey)
            public_numbers = key.public_numbers()
            try:
                curve_name = {
                    ec.SECP256R1: b"nistp256",
                    ec.SECP384R1: b"nistp384",
                    ec.SECP521R1: b"nistp521",
                }[type(public_numbers.curve)]
            except KeyError:
                raise ValueError(
                    "Only SECP256R1, SECP384R1, and SECP521R1 curves are "
                    "supported by the SSH public key format"
                )
            return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode(
                serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) +
                serialization._ssh_write_string(curve_name) +
                serialization._ssh_write_string(public_numbers.encode_point())
            )
项目:slack_scholar    作者:xLeitix    | 项目源码 | 文件源码
def _key_identifier_from_public_key(public_key):
    if isinstance(public_key, RSAPublicKey):
        data = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.PKCS1,
        )
    elif isinstance(public_key, EllipticCurvePublicKey):
        data = public_key.public_numbers().encode_point()
    else:
        # This is a very slow way to do this.
        serialized = public_key.public_bytes(
            serialization.Encoding.DER,
            serialization.PublicFormat.SubjectPublicKeyInfo
        )
        spki, remaining = decoder.decode(
            serialized, asn1Spec=_SubjectPublicKeyInfo()
        )
        assert not remaining
        # the univ.BitString object is a tuple of bits. We need bytes and
        # pyasn1 really doesn't want to give them to us. To get it we'll
        # build an integer and convert that to bytes.
        bits = 0
        for bit in spki.getComponentByName("subjectPublicKey"):
            bits = bits << 1 | bit

        data = utils.int_to_bytes(bits)

    return hashlib.sha1(data).digest()
项目:slack_scholar    作者:xLeitix    | 项目源码 | 文件源码
def public_key(self, key):
        """
        Sets the requestor's public key (as found in the signing request).
        """
        if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey,
                                ec.EllipticCurvePublicKey)):
            raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,'
                            ' or EllipticCurvePublicKey.')
        if self._public_key is not None:
            raise ValueError('The public key may only be set once.')
        return CertificateBuilder(
            self._issuer_name, self._subject_name, key,
            self._serial_number, self._not_valid_before,
            self._not_valid_after, self._extensions
        )
项目:delta-sdk-python    作者:Covata    | 项目源码 | 文件源码
def serialize_public_key(public_key):
    """
    Serializes the provided public key object as base-64-encoded DER format
    using X.509 SubjectPublicKeyInfo with PKCS1.

    :param public_key: the public key object
    :type public_key: :class:`~rsa.RSAPublicKey`
    :return: the key as base64 encoded unicode string
    :rtype: str
    """
    der = public_key.public_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)
    return base64.b64encode(der).decode(encoding='utf-8')
项目:delta-sdk-python    作者:Covata    | 项目源码 | 文件源码
def deserialize_public_key(b64_encoded_public_key):
    """
    loads a :class:`~rsa.RSAPublicKey` object from a serialized public key.

    :param str b64_encoded_public_key: the key as base64 encoded string
    :return: the public key object
    :rtype: :class:`~rsa.RSAPublicKey`
    """
    return serialization.load_der_public_key(
        data=base64.b64decode(b64_encoded_public_key.encode('utf-8')),
        backend=default_backend())
项目:delta-sdk-python    作者:Covata    | 项目源码 | 文件源码
def test_generate_private_key():
    private_key = crypto.generate_private_key()
    assert isinstance(private_key, rsa.RSAPrivateKey)
    public_key = private_key.public_key()
    assert isinstance(public_key, rsa.RSAPublicKey)
项目:delta-sdk-python    作者:Covata    | 项目源码 | 文件源码
def key2bytes():
    def convert(key):
        if isinstance(key, rsa.RSAPrivateKey):
            return key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption())
        elif isinstance(key, rsa.RSAPublicKey):
            der = key.public_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)
            return base64.b64encode(der).decode(encoding='utf-8')
    return convert
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def isPublic(self):
        """
        Check if this instance is a public key.

        @return: C{True} if this is a public key.
        """
        return isinstance(
            self._keyObject,
            (rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey))
项目:RemoteTree    作者:deNULL    | 项目源码 | 文件源码
def _openssh_public_key_bytes(self, key):
        if isinstance(key, rsa.RSAPublicKey):
            public_numbers = key.public_numbers()
            return b"ssh-rsa " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-rsa") +
                serialization._ssh_write_mpint(public_numbers.e) +
                serialization._ssh_write_mpint(public_numbers.n)
            )
        elif isinstance(key, dsa.DSAPublicKey):
            public_numbers = key.public_numbers()
            parameter_numbers = public_numbers.parameter_numbers
            return b"ssh-dss " + base64.b64encode(
                serialization._ssh_write_string(b"ssh-dss") +
                serialization._ssh_write_mpint(parameter_numbers.p) +
                serialization._ssh_write_mpint(parameter_numbers.q) +
                serialization._ssh_write_mpint(parameter_numbers.g) +
                serialization._ssh_write_mpint(public_numbers.y)
            )
        else:
            assert isinstance(key, ec.EllipticCurvePublicKey)
            public_numbers = key.public_numbers()
            try:
                curve_name = {
                    ec.SECP256R1: b"nistp256",
                    ec.SECP384R1: b"nistp384",
                    ec.SECP521R1: b"nistp521",
                }[type(public_numbers.curve)]
            except KeyError:
                raise ValueError(
                    "Only SECP256R1, SECP384R1, and SECP521R1 curves are "
                    "supported by the SSH public key format"
                )
            return b"ecdsa-sha2-" + curve_name + b" " + base64.b64encode(
                serialization._ssh_write_string(b"ecdsa-sha2-" + curve_name) +
                serialization._ssh_write_string(curve_name) +
                serialization._ssh_write_string(public_numbers.encode_point())
            )
项目:RemoteTree    作者:deNULL    | 项目源码 | 文件源码
def calculate_max_pss_salt_length(key, hash_algorithm):
    if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)):
        raise TypeError("key must be an RSA public or private key")
    # bit length - 1 per RFC 3447
    emlen = int(math.ceil((key.key_size - 1) / 8.0))
    salt_length = emlen - hash_algorithm.digest_size - 2
    assert salt_length >= 0
    return salt_length