class _CertificateBase():

    asn1 = None

    @property
    def algorithm(self):
        """
        :return:
            A unicode string of "rsa", "dsa" or "ec"
        """

        return self.public_key.algorithm

    @property
    def curve(self):
        """
        :return:
            A unicode string of EC curve name
        """

        return self.public_key.curve

    @property
    def bit_size(self):
        """
        :return:
            The number of bits in the public key, as an integer
        """

        return self.public_key.bit_size

    @property
    def byte_size(self):
        """
        :return:
            The number of bytes in the public key, as an integer
        """

        return self.public_key.byte_size def _fingerprint(key_object, load_private_key):
    """
    Returns a fingerprint used for correlating public keys and private keys

    :param key_object:
        An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo

    :raises:
        ValueError - when the key_object is not of the proper type

    ;return:
        A byte string fingerprint
    """

    if isinstance(key_object, PrivateKeyInfo):
        key = key_object['private_key'].parsed

        if key_object.algorithm == 'rsa':
            to_hash = '%d:%d' % (
                key['modulus'].native,
                key['public_exponent'].native,
            )

        elif key_object.algorithm == 'dsa':
            params = key_object['private_key_algorithm']['parameters']
            public_key = Integer(pow(
                params['g'].native,
                key_object['private_key'].parsed.native,
                params['p'].native
            ))

            to_hash = '%d:%d:%d:%d' % (
                params['p'].native,
                params['q'].native,
                params['g'].native,
                public_key.native,
            )

        elif key_object.algorithm == 'ec':
            public_key = key['public_key'].native
            if public_key is None:
                # This is gross, but since the EC public key is optional,
                # and we need to load the private key and use the crypto lib
                # to get the public key, we have to import the platform-specific
                # asymmetric implementation. This is the reason a bunch of the
                # imports are module imports, so we don't get an import cycle.
                public_key_object = load_private_key(key_object).public_key
                public_key = public_key_object.asn1['public_key'].parsed.native

            to_hash = '%s:' % key_object.curve[1]
            to_hash = to_hash.encode('utf-8')
            to_hash += public_key

        if isinstance(to_hash, str_cls):
            to_hash = to_hash.encode('utf-8')

        return hashlib.sha256(to_hash).digest()

    if isinstance(key_object, PublicKeyInfo):
        if key_object.algorithm == 'rsa':
            key = key_object['public_key'].parsed

            to_hash = '%d:%d' % (
                key['modulus'].native,
                key['public_exponent'].native,
            )

        elif key_object.algorithm == 'dsa':
            key = key_object['public_key'].parsed
            params = key_object['algorithm']['parameters']

            to_hash = '%d:%d:%d:%d' % (
                params['p'].native,
                params['q'].native,
                params['g'].native,
                key.native,
            )

        elif key_object.algorithm == 'ec':
            public_key = key_object['public_key'].native

            to_hash = '%s:' % key_object.curve[1]
            to_hash = to_hash.encode('utf-8')
            to_hash += public_key

        if isinstance(to_hash, str_cls):
            to_hash = to_hash.encode('utf-8')

        return hashlib.sha256(to_hash).digest()

    raise ValueError(pretty_message(
        '''
        key_object must be an instance of the
        asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo
        classes, not %s
        ''',
        type_name(key_object)
    )) def _parse_pkcs12(data, password, load_private_key):
    """
    Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys

    :param data:
        A byte string of a DER-encoded PKCS#12 file

    :param password:
        A byte string of the password to any encrypted data

    :param load_private_key:
        A callable that will accept a byte string and return an
        oscrypto.asymmetric.PrivateKey object

    :raises:
        ValueError - when any of the parameters are of the wrong type or value
        OSError - when an error is returned by one of the OS decryption functions

    :return:
        A three-element tuple of:
         1. An asn1crypto.keys.PrivateKeyInfo object
         2. An asn1crypto.x509.Certificate object
         3. A list of zero or more asn1crypto.x509.Certificate objects that are
            "extra" certificates, possibly intermediates from the cert chain
    """

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    if password is not None:
        if not isinstance(password, byte_cls):
            raise TypeError(pretty_message(
                '''
                password must be a byte string, not %s
                ''',
                type_name(password)
            ))
    else:
        password = b''

    certs = {}
    private_keys = {}

    pfx = Pfx.load(data)

    auth_safe = pfx['auth_safe']
    if auth_safe['content_type'].native != 'data':
        raise ValueError(pretty_message(
            '''
            Only password-protected PKCS12 files are currently supported
            '''
        ))
    authenticated_safe = pfx.authenticated_safe

    mac_data = pfx['mac_data']
    if mac_data:
        mac_algo = mac_data['mac']['digest_algorithm']['algorithm'].native
        key_length = {
            'sha1': 20,
            'sha224': 28,
            'sha256': 32,
            'sha384': 48,
            'sha512': 64,
            'sha512_224': 28,
            'sha512_256': 32,
        }[mac_algo]
        mac_key = pkcs12_kdf(
            mac_algo,
            password,
            mac_data['mac_salt'].native,
            mac_data['iterations'].native,
            key_length,
            3  # ID 3 is for generating an HMAC key
        )
        hash_mod = getattr(hashlib, mac_algo)
        computed_hmac = hmac.new(mac_key, auth_safe['content'].contents, hash_mod).digest()
        stored_hmac = mac_data['mac']['digest'].native
        if not constant_compare(computed_hmac, stored_hmac):
            raise ValueError('Password provided is invalid')

    for content_info in authenticated_safe:
        content = content_info['content']

        if isinstance(content, OctetString):
            _parse_safe_contents(content.native, certs, private_keys, password, load_private_key)

        elif isinstance(content, EncryptedData):
            encrypted_content_info = content['encrypted_content_info']

            encryption_algorithm_info = encrypted_content_info['content_encryption_algorithm']
            encrypted_content = encrypted_content_info['encrypted_content'].native
            decrypted_content = _decrypt_encrypted_data(encryption_algorithm_info, encrypted_content, password)

            _parse_safe_contents(decrypted_content, certs, private_keys, password, load_private_key)

        else:
            raise ValueError(pretty_message(
                '''
                Public-key-based PKCS12 files are not currently supported
                '''
            ))

    key_fingerprints = set(private_keys.keys())
    cert_fingerprints = set(certs.keys())

    common_fingerprints = sorted(list(key_fingerprints & cert_fingerprints))

    key = None
    cert = None
    other_certs = []

    if len(common_fingerprints) >= 1:
        fingerprint = common_fingerprints[0]
        key = private_keys[fingerprint]
        cert = certs[fingerprint]
        other_certs = [certs[f] for f in certs if f != fingerprint]
        return (key, cert, other_certs)

    if len(private_keys) > 0:
        first_key = sorted(list(private_keys.keys()))[0]
        key = private_keys[first_key]

    if len(certs) > 0:
        first_key = sorted(list(certs.keys()))[0]
        cert = certs[first_key]
        del certs[first_key]

    if len(certs) > 0:
        other_certs = sorted(list(certs.values()), key=lambda c: c.subject.human_friendly)

    return (key, cert, other_certs) class _PrivateKeyBase():

    asn1 = None
    _fingerprint = None

    def unwrap(self):
        """
        Unwraps the private key into an asn1crypto.keys.RSAPrivateKey,
        asn1crypto.keys.DSAPrivateKey or asn1crypto.keys.ECPrivateKey object

        :return:
            An asn1crypto.keys.RSAPrivateKey, asn1crypto.keys.DSAPrivateKey or
            asn1crypto.keys.ECPrivateKey object
        """

        if self.algorithm == 'rsa':
            return self.asn1['private_key'].parsed

        if self.algorithm == 'dsa':
            params = self.asn1['private_key_algorithm']['parameters']
            return DSAPrivateKey({
                'version': 0,
                'p': params['p'],
                'q': params['q'],
                'g': params['g'],
                'public_key': self.public_key.unwrap(),
                'private_key': self.asn1['private_key'].parsed,
            })

        if self.algorithm == 'ec':
            output = self.asn1['private_key'].parsed
            output['parameters'] = self.asn1['private_key_algorithm']['parameters']
            output['public_key'] = self.public_key.unwrap()
            return output

    @property
    def algorithm(self):
        """
        :return:
            A unicode string of "rsa", "dsa" or "ec"
        """

        return self.asn1.algorithm

    @property
    def curve(self):
        """
        :return:
            A unicode string of EC curve name
        """

        return self.asn1.curve[1]

    @property
    def bit_size(self):
        """
        :return:
            The number of bits in the key, as an integer
        """

        return self.asn1.bit_size

    @property
    def byte_size(self):
        """
        :return:
            The number of bytes in the key, as an integer
        """

        return self.asn1.byte_size class _PublicKeyBase():

    asn1 = None
    _fingerprint = None

    def unwrap(self):
        """
        Unwraps a public key into an asn1crypto.keys.RSAPublicKey,
        asn1crypto.core.Integer (for DSA) or asn1crypto.keys.ECPointBitString
        object

        :return:
            An asn1crypto.keys.RSAPublicKey, asn1crypto.core.Integer or
            asn1crypto.keys.ECPointBitString object
        """

        if self.algorithm == 'ec':
            return self.asn1['public_key']
        return self.asn1['public_key'].parsed

    @property
    def fingerprint(self):
        """
        Creates a fingerprint that can be compared with a private key to see if
        the two form a pair.

        This fingerprint is not compatible with fingerprints generated by any
        other software.

        :return:
            A byte string that is a sha256 hash of selected components (based
            on the key type)
        """

        if self._fingerprint is None:
            self._fingerprint = _fingerprint(self.asn1, None)
        return self._fingerprint

    @property
    def algorithm(self):
        """
        :return:
            A unicode string of "rsa", "dsa" or "ec"
        """

        return self.asn1.algorithm

    @property
    def curve(self):
        """
        :return:
            A unicode string of EC curve name
        """

        return self.asn1.curve[1]

    @property
    def bit_size(self):
        """
        :return:
            The number of bits in the key, as an integer
        """

        return self.asn1.bit_size

    @property
    def byte_size(self):
        """
        :return:
            The number of bytes in the key, as an integer
        """

        return self.asn1.byte_size def _unwrap_private_key_info(key_info):
    """
    Unwraps an asn1crypto.keys.PrivateKeyInfo object into an
    asn1crypto.keys.RSAPrivateKey, asn1crypto.keys.DSAPrivateKey
    or asn1crypto.keys.ECPrivateKey.

    :param key_info:
        An asn1crypto.keys.PrivateKeyInfo object

    :return:
        One of:
         - asn1crypto.keys.RSAPrivateKey
         - asn1crypto.keys.DSAPrivateKey
         - asn1crypto.keys.ECPrivateKey
    """

    if key_info.algorithm == 'rsa':
        return key_info['private_key'].parsed

    if key_info.algorithm == 'dsa':
        params = key_info['private_key_algorithm']['parameters']
        parsed = key_info['private_key'].parsed
        return DSAPrivateKey({
            'version': 0,
            'p': params['p'],
            'q': params['q'],
            'g': params['g'],
            'public_key': Integer(pow(
                params['g'].native,
                parsed.native,
                params['p'].native
            )),
            'private_key': parsed,
        })

    if key_info.algorithm == 'ec':
        parsed = key_info['private_key'].parsed
        parsed['parameters'] = key_info['private_key_algorithm']['parameters']
        return parsed

    raise ValueError('Unsupported key_info.algorithm "%s"' % key_info.algorithm) def parse_certificate(data):
    """
    Loads a certificate from a DER or PEM-formatted file. Supports X.509
    certificates only.

    :param data:
        A byte string to load the certificate from

    :raises:
        ValueError - when the data does not appear to contain a certificate

    :return:
        An asn1crypto.x509.Certificate object
    """

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    key_type = None

    # Appears to be PEM formatted
    if re.match(b'\\s*-----', data) is not None:
        key_type, _, data = _unarmor_pem(data)

        if key_type == 'private key':
            raise ValueError(pretty_message(
                '''
                The data specified does not appear to be a certificate, but
                rather a private key
                '''
            ))

        if key_type == 'public key':
            raise ValueError(pretty_message(
                '''
                The data specified does not appear to be a certificate, but
                rather a public key
                '''
            ))

    if key_type is None or key_type == 'certificate':
        try:
            return Certificate.load(data)
        except (ValueError):
            pass  # Data was not a Certificate

    raise ValueError(pretty_message(
        '''
        The data specified does not appear to be a known certificate format
        '''
    )) def parse_private(data, password=None):
    """
    Loads a private key from a DER or PEM-formatted file. Supports RSA, DSA and
    EC private keys. Works with the follow formats:

     - RSAPrivateKey (PKCS#1)
     - ECPrivateKey (SECG SEC1 V2)
     - DSAPrivateKey (OpenSSL)
     - PrivateKeyInfo (RSA/DSA/EC - PKCS#8)
     - EncryptedPrivateKeyInfo (RSA/DSA/EC - PKCS#8)
     - Encrypted RSAPrivateKey (PEM only, OpenSSL)
     - Encrypted DSAPrivateKey (PEM only, OpenSSL)
     - Encrypted ECPrivateKey (PEM only, OpenSSL)

    :param data:
        A byte string to load the private key from

    :param password:
        The password to unencrypt the private key

    :raises:
        ValueError - when the data does not appear to contain a private key, or the password is invalid

    :return:
        An asn1crypto.keys.PrivateKeyInfo object
    """

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    if password is not None:
        if not isinstance(password, byte_cls):
            raise TypeError(pretty_message(
                '''
                password must be a byte string, not %s
                ''',
                type_name(password)
            ))
    else:
        password = b''

    # Appears to be PEM formatted
    if re.match(b'\\s*-----', data) is not None:
        key_type, _, data = _unarmor_pem(data, password)

        if key_type == 'public key':
            raise ValueError(pretty_message(
                '''
                The data specified does not appear to be a private key, but
                rather a public key
                '''
            ))

        if key_type == 'certificate':
            raise ValueError(pretty_message(
                '''
                The data specified does not appear to be a private key, but
                rather a certificate
                '''
            ))

    try:
        pki = PrivateKeyInfo.load(data)
        # Call .native to fully parse since asn1crypto is lazy
        pki.native
        return pki
    except (ValueError):
        pass  # Data was not PrivateKeyInfo

    try:
        parsed_wrapper = EncryptedPrivateKeyInfo.load(data)
        encryption_algorithm_info = parsed_wrapper['encryption_algorithm']
        encrypted_data = parsed_wrapper['encrypted_data'].native
        decrypted_data = _decrypt_encrypted_data(encryption_algorithm_info, encrypted_data, password)
        pki = PrivateKeyInfo.load(decrypted_data)
        # Call .native to fully parse since asn1crypto is lazy
        pki.native
        return pki
    except (ValueError):
        pass  # Data was not EncryptedPrivateKeyInfo

    try:
        parsed = RSAPrivateKey.load(data)
        # Call .native to fully parse since asn1crypto is lazy
        parsed.native
        return PrivateKeyInfo.wrap(parsed, 'rsa')
    except (ValueError):
        pass  # Data was not an RSAPrivateKey

    try:
        parsed = DSAPrivateKey.load(data)
        # Call .native to fully parse since asn1crypto is lazy
        parsed.native
        return PrivateKeyInfo.wrap(parsed, 'dsa')
    except (ValueError):
        pass  # Data was not a DSAPrivateKey

    try:
        parsed = ECPrivateKey.load(data)
        # Call .native to fully parse since asn1crypto is lazy
        parsed.native
        return PrivateKeyInfo.wrap(parsed, 'ec')
    except (ValueError):
        pass  # Data was not an ECPrivateKey

    raise ValueError(pretty_message(
        '''
        The data specified does not appear to be a known private key format
        '''
    )) def parse_public(data):
    """
    Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
    EC public keys. For RSA keys, both the old RSAPublicKey and
    SubjectPublicKeyInfo structures are supported. Also allows extracting a
    public key from an X.509 certificate.

    :param data:
        A byte string to load the public key from

    :raises:
        ValueError - when the data does not appear to contain a public key

    :return:
        An asn1crypto.keys.PublicKeyInfo object
    """

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    key_type = None

    # Appears to be PEM formatted
    if re.match(b'\\s*-----', data) is not None:
        key_type, algo, data = _unarmor_pem(data)

        if key_type == 'private key':
            raise ValueError(pretty_message(
                '''
                The data specified does not appear to be a public key or
                certificate, but rather a private key
                '''
            ))

        # When a public key returning from _unarmor_pem has a known algorithm
        # of RSA, that means the DER structure is of the type RSAPublicKey, so
        # we need to wrap it in the PublicKeyInfo structure.
        if algo == 'rsa':
            return PublicKeyInfo.wrap(data, 'rsa')

    if key_type is None or key_type == 'public key':
        try:
            pki = PublicKeyInfo.load(data)
            # Call .native to fully parse since asn1crypto is lazy
            pki.native
            return pki
        except (ValueError):
            pass  # Data was not PublicKeyInfo

        try:
            rpk = RSAPublicKey.load(data)
            # Call .native to fully parse since asn1crypto is lazy
            rpk.native
            return PublicKeyInfo.wrap(rpk, 'rsa')
        except (ValueError):
            pass  # Data was not an RSAPublicKey

    if key_type is None or key_type == 'certificate':
        try:
            parsed_cert = Certificate.load(data)
            key_info = parsed_cert['tbs_certificate']['subject_public_key_info']
            return key_info
        except (ValueError):
            pass  # Data was not a cert

    raise ValueError('The data specified does not appear to be a known public key or certificate format') def buffer_from_bytes(initializer):
    if sys.platform == 'win32':
        return ffi.new('unsigned char[]', initializer)
    return ffi.new('char[]', initializer) def buffer_pointer(buffer):
    return ffi.new('char *[]', [buffer]) def bytes_from_buffer(buffer, maxlen=None):
    if maxlen is not None:
        return ffi.buffer(buffer, maxlen)[:]
    return ffi.buffer(buffer)[:] def deref(point):
    return point[0] def is_null(point):
    if point is None:
        return True
    if point == ffi.NULL:
        return True
    if ffi.getctype(ffi.typeof(point)) == 'void *':
        return False
    if point[0] == ffi.NULL:
        return True
    return False def new(library, type_, value=None):
    ffi_obj = _get_ffi(library)

    params = []
    if value is not None:
        params.append(value)
    if type_ in set(['BCRYPT_KEY_HANDLE', 'BCRYPT_ALG_HANDLE']):
        return ffi_obj.cast(type_, 0)
    return ffi_obj.new(type_, *params) def null():
    return ffi.NULL def unwrap(point):
    return point[0] def _try_decode(value):
def handle_openssl_error(result, exception_class=None):
def peek_openssl_error():
class LibcryptoConst():
    EVP_CTRL_SET_RC2_KEY_BITS = 3
    SSLEAY_VERSION = 0
    RSA_PKCS1_PADDING = 1
    RSA_NO_PADDING = 3
    RSA_PKCS1_OAEP_PADDING = 4
    EVP_MD_CTX_FLAG_PSS_MDLEN = -1
    EVP_PKEY_CTRL_RSA_PADDING = 0x1001
    RSA_PKCS1_PSS_PADDING = 6
    EVP_PKEY_CTRL_RSA_PSS_SALTLEN = 0x1002
    EVP_PKEY_RSA = 6
    EVP_PKEY_OP_SIGN = 1 << 3
    EVP_PKEY_OP_VERIFY = 1 << 4
    OPENSSL_EC_NAMED_CURVE = 1
    DH_GENERATOR_2 = 2 class AsymmetricKeyError(Exception):

    """
    An exception when a key is invalid or unsupported
    """

    pass class IncompleteAsymmetricKeyError(AsymmetricKeyError):

    """
    An exception when a key is missing necessary information
    """

    pass class SignatureError(Exception):

    """
    An exception when validating a signature
    """

    pass def constant_compare(a, b):
    """
    Compares two byte strings in constant time to see if they are equal

    :param a:
        The first byte string

    :param b:
        The second byte string

    :return:
        A boolean if the two byte strings are equal
    """

    if not isinstance(a, byte_cls):
        raise TypeError(pretty_message(
            '''
            a must be a byte string, not %s
            ''',
            type_name(a)
        ))

    if not isinstance(b, byte_cls):
        raise TypeError(pretty_message(
            '''
            b must be a byte string, not %s
            ''',
            type_name(b)
        ))

    if len(a) != len(b):
        return False

    if sys.version_info < (3,):
        a = [ord(char) for char in a]
        b = [ord(char) for char in b]

    result = 0
    for x, y in zip(a, b):
        result |= x ^ y
    return result == 0
import hashlib
from .._asn1 import (
    Certificate as Asn1Certificate,
    DHParameters,
    ECDomainParameters,
    PrivateKeyInfo,
    PublicKeyAlgorithm,
    PublicKeyInfo,
)
from .._asymmetric import (
    _CertificateBase,
    _fingerprint,
    _parse_pkcs12,
    _PrivateKeyBase,
    _PublicKeyBase,
    _unwrap_private_key_info,
    parse_certificate,
    parse_private,
    parse_public,
)
from .._errors import pretty_message
from .._ffi import (
    buffer_from_bytes,
    buffer_pointer,
    bytes_from_buffer,
    deref,
    is_null,
    new,
    null,
    unwrap,
)
from ._libcrypto import libcrypto, LibcryptoConst, libcrypto_version_info, handle_openssl_error
from ..errors import AsymmetricKeyError, IncompleteAsymmetricKeyError, SignatureError
from .._types import type_name, str_cls, byte_cls, int_types
from ..util import constant_compare

    if certificate_or_public_key.algorithm != 'ec':
        raise ValueError(pretty_message(
            '''
            The key specified is not an EC public key, but %s
            ''',
            certificate_or_public_key.algorithm.upper()
        ))

    return _verify(certificate_or_public_key, signature, data, hash_algorithm)


def _verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):
    """
    Verifies an RSA, DSA or ECDSA signature

    :param certificate_or_public_key:
        A Certificate or PublicKey instance to verify the signature with

    :param signature:
        A byte string of the signature to verify

    :param data:
        A byte string of the data the signature is for

    :param hash_algorithm:
        A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"

    :param rsa_pss_padding:
        If the certificate_or_public_key is an RSA key, this enables PSS padding

    :raises:
        oscrypto.errors.SignatureError - when the signature is determined to be invalid
        ValueError - when any of the parameters contain an invalid value
        TypeError - when any of the parameters are of the wrong type
        OSError - when an error is returned by the OS crypto library
    """

    if not isinstance(certificate_or_public_key, (Certificate, PublicKey)):
        raise TypeError(pretty_message(
            '''
            certificate_or_public_key must be an instance of the Certificate or
            PublicKey class, not %s
            ''',
            type_name(certificate_or_public_key)
        ))

    if not isinstance(signature, byte_cls):
        raise TypeError(pretty_message(
            '''
            signature must be a byte string, not %s
            ''',
            type_name(signature)
        ))

    if not isinstance(data, byte_cls):
        raise TypeError(pretty_message(
            '''
            data must be a byte string, not %s
            ''',
            type_name(data)
        ))

    valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'])
    if certificate_or_public_key.algorithm == 'rsa' and not rsa_pss_padding:
        valid_hash_algorithms |= set(['raw'])

    if hash_algorithm not in valid_hash_algorithms:
        valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"'
        if certificate_or_public_key.algorithm == 'rsa' and not rsa_pss_padding:
            valid_hash_algorithms_error += ', "raw"'
        raise ValueError(pretty_message(
            '''
            hash_algorithm must be one of %s, not %s
            ''',
            valid_hash_algorithms_error,
            repr(hash_algorithm)
        ))

    if certificate_or_public_key.algorithm != 'rsa' and rsa_pss_padding:
        raise ValueError(pretty_message(
            '''
            PSS padding can only be used with RSA keys - the key provided is a
            %s key
            ''',
            certificate_or_public_key.algorithm.upper()
        ))

    if certificate_or_public_key.algorithm == 'rsa' and hash_algorithm == 'raw':
        if len(data) > certificate_or_public_key.byte_size - 11:
            raise ValueError(pretty_message(
                '''
                data must be 11 bytes shorter than the key size when
                hash_algorithm is "raw" - key size is %s bytes, but data is
                %s bytes long
                ''',
                certificate_or_public_key.byte_size,
                len(data)
            ))

        rsa = None

        try:
            rsa = libcrypto.EVP_PKEY_get1_RSA(certificate_or_public_key.evp_pkey)
            if is_null(rsa):
                handle_openssl_error(0)

            buffer_size = _evp_pkey_get_size(certificate_or_public_key.evp_pkey)
            decrypted_buffer = buffer_from_bytes(buffer_size)
            decrypted_length = libcrypto.RSA_public_decrypt(
                len(signature),
                signature,
                decrypted_buffer,
                rsa,
                LibcryptoConst.RSA_PKCS1_PADDING
            )
            handle_openssl_error(decrypted_length)

            decrypted_bytes = bytes_from_buffer(decrypted_buffer, decrypted_length)


            if not constant_compare(data, decrypted_bytes):