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


Python serialization.load_pem_public_key方法代码示例

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


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

示例1: rsa_encrypt

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def rsa_encrypt(data, pem, b64_encode=True):
    """
    rsa 加密
    :param data: 待加密字符串/binary
    :param pem: RSA public key 内容/binary
    :param b64_encode: 是否对输出进行 base64 encode
    :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode("utf-8")
    return encrypted_data 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:24,代码来源:utils.py

示例2: convert_pem_to_der

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def convert_pem_to_der(pem_key):
    """
    Converts a given key from PEM to DER format.

    :param pem_key: PEM-encoded key bytes
    :type pem_key: bytearray
    :return: DER-encoded key bytes
    :rtype: bytearray
    """
    first_line = pem_key.decode().split('\n', 1)[0]
    is_private = first_line == begin_key.format(private_str)
    if is_private:
        loaded_key = crypto_serialization.load_pem_private_key(pem_key, backend=crypto_default_backend())
        return serialize_key(loaded_key, encoding='DER', return_private=is_private)
    else:
        loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend=crypto_default_backend())
        return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.DER,
                                       format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo) 
开发者ID:aws,项目名称:aws-ec2-instance-connect-cli,代码行数:20,代码来源:key_utils.py

示例3: __init__

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def __init__(self, wrapping_algorithm, wrapping_key, wrapping_key_type, password=None):
        """Prepares initial values."""
        self.wrapping_algorithm = wrapping_algorithm
        self.wrapping_key_type = wrapping_key_type
        if wrapping_key_type is EncryptionKeyType.PRIVATE:
            self._wrapping_key = serialization.load_pem_private_key(
                data=wrapping_key, password=password, backend=default_backend()
            )
        elif wrapping_key_type is EncryptionKeyType.PUBLIC:
            self._wrapping_key = serialization.load_pem_public_key(data=wrapping_key, backend=default_backend())
        elif wrapping_key_type is EncryptionKeyType.SYMMETRIC:
            self._wrapping_key = wrapping_key
            self._derived_wrapping_key = derive_data_encryption_key(
                source_key=self._wrapping_key, algorithm=self.wrapping_algorithm.algorithm, message_id=None
            )
        else:
            raise InvalidDataKeyError("Invalid wrapping_key_type: {}".format(wrapping_key_type)) 
开发者ID:aws,项目名称:aws-encryption-sdk-python,代码行数:19,代码来源:wrapping_keys.py

示例4: set_rpc_encryption_pubkey

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def set_rpc_encryption_pubkey(self, key: str):
        """
        AES public key for additional RPC encryption, dedicated for calls transmitting sensitive information
        like protx. Accepted formats: PEM, DER.
        """
        try:
            if key:
                # validate public key by deserializing it
                if re.fullmatch(r'^([0-9a-fA-F]{2})+$', key):
                    serialization.load_der_public_key(bytes.fromhex(key), backend=default_backend())
                else:
                    pubkey = serialization.load_pem_public_key(key.encode('ascii'), backend=default_backend())
                    raw = pubkey.public_bytes(serialization.Encoding.DER,
                                              format=serialization.PublicFormat.SubjectPublicKeyInfo)
                    key = raw.hex()

            if self.__rpc_encryption_pubkey_object and (self.__rpc_encryption_pubkey_der != key or not key):
                self.__rpc_encryption_pubkey_der = None

            self.__rpc_encryption_pubkey_der = key
        except Exception as e:
            logging.exception('Exception occurred')
            raise 
开发者ID:Bertrand256,项目名称:dash-masternode-tool,代码行数:25,代码来源:app_config.py

示例5: sha2_rsa_encrypt

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def sha2_rsa_encrypt(password, salt, public_key):
    """Encrypt password with salt and public_key.

    Used for sha256_password and caching_sha2_password.
    """
    if not _have_cryptography:
        raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")
    message = _xor_password(password + b'\0', salt)
    rsa_key = serialization.load_pem_public_key(public_key, default_backend())
    return rsa_key.encrypt(
        message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        ),
    ) 
开发者ID:tp4a,项目名称:teleport,代码行数:19,代码来源:_auth.py

示例6: __init__

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def __init__(self, public_key_filename: str, pre_err_handler: Callable[[str], None] = None) -> None:
        """Initializes a Trust object. A Trust object represents a public key and related utility methods on that key.
        If the application only has a single public key, it's best to use 'getInstance' or 'getInstanceOrNone'.

        :param public_key_filename: Path to the file that holds the public key.
        :param pre_err_handler: An extra error handler which will be called before TrustBasics.defaultViolationHandler
                                Receives a human readable error string as argument.
        :raise Exception: if public key file provided by the argument can't be found or parsed.
        """

        self._public_key = None  # type: Optional[RSAPublicKey]
        try:
            with open(public_key_filename, "rb") as file:
                self._public_key = load_pem_public_key(file.read(), backend = default_backend())
        except:  # Yes, we  do really want this on _every_ exception that might occur.
            self._public_key = None
            raise Exception("e", "Couldn't load public-key '{0}'.".format(public_key_filename))
            # NOTE: Handle _potential_ security violation outside of this initializer, in case it's just for validation.

        def violation_handler(message: str):
            if pre_err_handler is not None:
                pre_err_handler(message)
            TrustBasics.defaultViolationHandler(message=message)

        self._violation_handler = violation_handler  # type: Callable[[str], None] 
开发者ID:Ultimaker,项目名称:Uranium,代码行数:27,代码来源:Trust.py

示例7: _rsa_public_numbers

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def _rsa_public_numbers(public_key_data):
    """
    Take the data for a public key (string of the key in PEM format) and return
    the public key modulus ``n`` and exponent ``e`` for that key.

    The values of n and e are needed for the return of the JWKS endpoint.

    Args:
        public_key_data (str): the public key

    Return:
        Tuple[int, int]: the public key modulus ``n`` and exponent ``e``
    """
    key = serialization.load_pem_public_key(
        bytes(public_key_data, "utf-8"), default_backend()
    )
    numbers = key.public_numbers()
    return (numbers.n, numbers.e) 
开发者ID:uc-cdis,项目名称:fence,代码行数:20,代码来源:keys.py

示例8: __init_crypto

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def __init_crypto(self):
        # https://stackoverflow.com/questions/29650495/how-to-verify-a-jwt-using-python-pyjwt-with-public-key
        with self.app.app_context():
            with open('{}/keys/appkernel.pem'.format(self.cfg_dir), "rb") as key_file:
                private_key = serialization.load_pem_private_key(
                    key_file.read(),
                    password=None,
                    backend=default_backend()
                )
                config.private_key = private_key
            with open('{}/keys/appkernel.pub'.format(self.cfg_dir), 'rb') as key_file:
                public_key = serialization.load_pem_public_key(
                    key_file.read(),
                    backend=default_backend()
                )
                config.public_key = public_key 
开发者ID:accelero-cloud,项目名称:appkernel,代码行数:18,代码来源:engine.py

示例9: validate_public_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def validate_public_key(value):
    """
    Check that the given value is a valid RSA Public key in either PEM or OpenSSH format. If it is invalid,
    raises ``django.core.exceptions.ValidationError``.
    """
    is_valid = False
    exc = None

    for load in (load_pem_public_key, load_ssh_public_key):
        if not is_valid:
            try:
                load(value.encode('utf-8'), default_backend())
                is_valid = True
            except Exception as e:
                exc = e

    if not is_valid:
        raise ValidationError('Public key is invalid: %s' % exc) 
开发者ID:crgwbr,项目名称:asymmetric-jwt-auth,代码行数:20,代码来源:models.py

示例10: _get_secret_data

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def _get_secret_data(self, secret):
        """Retrieves the secret data.

        Converts the Barbican secret to bytes suitable for a Castellan object.
        If the secret is a public key, private key, or certificate, the secret
        is expected to be in PEM format and will be converted to DER.

        :param secret: the secret from barbican with the payload of data
        :returns: the secret data
        """
        if secret.secret_type == 'public':
            key = serialization.load_pem_public_key(
                secret.payload,
                backend=backends.default_backend())
            return key.public_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PublicFormat.SubjectPublicKeyInfo)
        elif secret.secret_type == 'private':
            key = serialization.load_pem_private_key(
                secret.payload,
                backend=backends.default_backend(),
                password=None)
            return key.private_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption())
        elif secret.secret_type == 'certificate':
            cert = cryptography_x509.load_pem_x509_certificate(
                secret.payload,
                backend=backends.default_backend())
            return cert.public_bytes(encoding=serialization.Encoding.DER)
        else:
            return secret.payload 
开发者ID:openstack,项目名称:castellan,代码行数:35,代码来源:barbican_key_manager.py

示例11: import_from_pem

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def import_from_pem(self, data, password=None):
        """Imports a key from data loaded from a PEM file.
        The key may be encrypted with a password.
        Private keys (PKCS#8 format), public keys, and X509 certificate's
        public keys can be imported with this interface.

        :param data(bytes): The data contained in a PEM file.
        :param password(bytes): An optional password to unwrap the key.
        """

        try:
            key = serialization.load_pem_private_key(
                data, password=password, backend=default_backend())
        except ValueError as e:
            if password is not None:
                raise e
            try:
                key = serialization.load_pem_public_key(
                    data, backend=default_backend())
            except ValueError:
                try:
                    cert = x509.load_pem_x509_certificate(
                        data, backend=default_backend())
                    key = cert.public_key()
                except ValueError:
                    raise e

        self.import_from_pyca(key)
        self._params['kid'] = self.thumbprint() 
开发者ID:latchset,项目名称:jwcrypto,代码行数:31,代码来源:jwk.py

示例12: load_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def load_key(pubkey):
    """Load public RSA key, with work-around for keys using
    incorrect header/footer format.

    Read more about RSA encryption with cryptography:
    https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
    """
    try:
        return load_pem_public_key(pubkey.encode(), default_backend())
    except ValueError:
        # workaround for https://github.com/travis-ci/travis-api/issues/196
        pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
        return load_pem_public_key(pubkey.encode(), default_backend()) 
开发者ID:decentfox,项目名称:aioh2,代码行数:15,代码来源:travis_pypi_setup.py

示例13: convert_pem_to_openssh

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def convert_pem_to_openssh(pem_key):
    """
    Converts a given public key from PEM to OpenSSH format.

    :param pem_key: PEM-encoded key bytes
    :type pem_key: bytearray
    :return: OpenSSH-encoded key bytes
    :rtype: bytearray
    """
    loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend=crypto_default_backend())
    return loaded_key.public_bytes(encoding=crypto_serialization.Encoding.OpenSSH,
                                   format=crypto_serialization.PublicFormat.OpenSSH) 
开发者ID:aws,项目名称:aws-ec2-instance-connect-cli,代码行数:14,代码来源:key_utils.py

示例14: __init__

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def __init__(self, private_key=None, public_key=None):
        """
        :param private_key: The private Key data in PEM format
        :type private_key: bytes or None
        :param public_key:  The public key data in PEM format
        :type public_key: bytes or None
        :return: Sign Object
        """
        self.private = None
        self.public = None
        backend = default_backend()
        if private_key:
            try:
                self.private = serialization.load_pem_private_key(private_key,
                                                                  password=None,
                                                                  backend=backend)
            except Exception as e:
                log.error("Error loading private key: ({0!r})".format(e))
                log.debug(traceback.format_exc())
                raise e

        if public_key:
            try:
                self.public = serialization.load_pem_public_key(public_key,
                                                                backend=backend)
            except Exception as e:
                log.error("Error loading public key: ({0!r})".format(e))
                log.debug(traceback.format_exc())
                raise e 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:31,代码来源:crypto.py

示例15: load_key

# 需要导入模块: from cryptography.hazmat.primitives import serialization [as 别名]
# 或者: from cryptography.hazmat.primitives.serialization import load_pem_public_key [as 别名]
def load_key(pubkey):
    """Load public RSA key.

    Work around keys with incorrect header/footer format.

    Read more about RSA encryption with cryptography:
    https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
    """
    try:
        return load_pem_public_key(pubkey.encode(), default_backend())
    except ValueError:
        # workaround for https://github.com/travis-ci/travis-api/issues/196
        pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
        return load_pem_public_key(pubkey.encode(), default_backend()) 
开发者ID:Nekmo,项目名称:telegram-upload,代码行数:16,代码来源:travis_pypi_setup.py


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