How to use the cryptography.hazmat.primitives.serialization.load_pem_private_key function in cryptography

To help you get started, we’ve selected a few cryptography examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyca / cryptography / tests / hazmat / primitives / test_serialization.py View on Github external
FPZk/7x0xmdsTPECSWnHK+HhoaNDFPR3j8jQhVo1laxiqcEhAHegi5cwtFosuJAv
        FiRC0Cgz+frQPFQEBsAV9RuasyQxqzxrR0Ow0qncBeGBWbYE6WZhqtcLAI895b+i
        +F4lbB4iD7T9QeIDMU/aIMXA81UO4cns1z4qDAHKeyLLrPQrJ/B4X7XC+egUWm5+
        hr1qmyAMusyXIBECQQDJWZ8piluf4yrYfsJAn6hF5T4RjTztbqvO0GVG2McHY7Uj
        NPSffhzHx/ll0fQEQji+OgydCCX8o3HZrgw5YfSJAkEA7e+rqdU5nO5ZG//PSEQb
        tjLnRiTzBH/elQhtdZ5nF7pcpNTi4k13zutmKcWW4GK75azcRGJUhu1kDM7QYAOd
        SQJAVNkYcifkvna7GmooL5VYEsQsqLbM4v0NF2TIGNfG3z1MGp75KrC5LhL97MNR
        we2p/bd2k0HYyCKUGnf2nMPDiQJBAI75pwittSoE240EobUGIDTSz8CJsXIxuDmL
        z+KOpdpPRR5TQmbEMEspjsFpFymMiuYPgmihQbO2cJl1qScY5OkCQQCJ6m5tcN8l
        Xxg/SNpjEIv+qAyUD96XVlOJlOIeLHQ8kYE0C6ZA+MsqYIzgAreJk88Yn0lU/X0/
        mu/UpE/BRZmR
        -----END PRIVATE KEY-----
        """).encode()

        with pytest.raises(ValueError):
            load_pem_private_key(
                key_data, None, backend
            )

        with pytest.raises(ValueError):
            load_pem_private_key(
                key_data, b"this password will not be used", backend
            )
github oracle / oci-python-sdk / src / oci / _vendor / httpsig_cffi / sign.py View on Github external
if algorithm is None:
            algorithm = DEFAULT_SIGN_ALGORITHM

        assert algorithm in ALGORITHMS, "Unknown algorithm"  # noqa: F405
        if isinstance(secret, six.string_types):
            secret = secret.encode("ascii")

        self._rsa_public = None
        self._rsa_private = None
        self._hash = None
        self.sign_algorithm, self.hash_algorithm = algorithm.split('-')

        if self.sign_algorithm == 'rsa':
            try:
                self._rsahash = HASHES[self.hash_algorithm]  # noqa: 405
                self._rsa_private = serialization.load_pem_private_key(
                    secret,
                    None,
                    backend=default_backend()
                )
                self._rsa_public = self._rsa_private.public_key()
            except ValueError as e:  # noqa: F841
                try:
                    self._rsa_public = serialization.load_pem_public_key(
                        secret,
                        backend=default_backend()
                    )
                except ValueError as e:  # noqa: F841
                    raise HttpSigException("Invalid key.")  # noqa: 405
        elif self.sign_algorithm == 'hmac':
            self._hash = hmac.HMAC(
                secret,
github nanassito / SharedVault / sharedvault / crypto / asymetric.py View on Github external
def deserialize_private_key(
    private_key_bytes: bytes, password: bytes
) -> _RSAPrivateKey:
    return serialization.load_pem_private_key(
        private_key_bytes, password=password, backend=default_backend()
    )
github celery / celery / celery / security / key.py View on Github external
def __init__(self, key, password=None):
        with reraise_errors(
            'Invalid private key: {0!r}', errors=(ValueError,)
        ):
            self._key = serialization.load_pem_private_key(
                ensure_bytes(key),
                password=password,
                backend=default_backend())
github komuw / sewer / sewer / client.py View on Github external
def get_acme_header(self, url):
        """
        https://tools.ietf.org/html/draft-ietf-acme-acme#section-6.2
        The JWS Protected Header MUST include the following fields:
        - "alg" (Algorithm)
        - "jwk" (JSON Web Key, only for requests to new-account and revoke-cert resources)
        - "kid" (Key ID, for all other requests). gotten from self.ACME_NEW_ACCOUNT_URL
        - "nonce". gotten from self.ACME_GET_NONCE_URL
        - "url"
        """
        self.logger.debug("get_acme_header")
        header = {"alg": "RS256", "nonce": self.get_nonce(), "url": url}
        if url in [self.ACME_NEW_ACCOUNT_URL, self.ACME_REVOKE_CERT_URL, "GET_THUMBPRINT"]:
            private_key = cryptography.hazmat.primitives.serialization.load_pem_private_key(
                self.account_key.encode(),
                password=None,
                backend=cryptography.hazmat.backends.default_backend(),
            )
            public_key_public_numbers = private_key.public_key().public_numbers()
            # private key public exponent in hex format
            exponent = "{0:x}".format(public_key_public_numbers.e)
            exponent = "0{0}".format(exponent) if len(exponent) % 2 else exponent
            # private key modulus in hex format
            modulus = "{0:x}".format(public_key_public_numbers.n)
            jwk = {
                "kty": "RSA",
                "e": self.calculate_safe_base64(binascii.unhexlify(exponent)),
                "n": self.calculate_safe_base64(binascii.unhexlify(modulus)),
            }
            header["jwk"] = jwk
github ansible / ansible / lib / ansible / module_utils / crypto.py View on Github external
crypto.load_privatekey(crypto.FILETYPE_PEM,
                                           priv_key_detail,
                                           to_bytes('y' if passphrase == 'x' else 'x'))
                    if passphrase is not None:
                        # Since we can load the key without an exception, the
                        # key isn't password-protected
                        raise OpenSSLBadPassphraseError('Passphrase provided, but private key is not password-protected!')
                except crypto.Error as e:
                    if passphrase is None and len(e.args) > 0 and len(e.args[0]) > 0:
                        if e.args[0][0][2] in ('bad decrypt', 'bad password read'):
                            # The key is obviously protected by the empty string.
                            # Don't do this at home (if it's possible at all)...
                            raise OpenSSLBadPassphraseError('No passphrase provided, but private key is password-protected!')
        elif backend == 'cryptography':
            try:
                result = load_pem_private_key(priv_key_detail,
                                              None if passphrase is None else to_bytes(passphrase),
                                              cryptography_backend())
            except TypeError as dummy:
                raise OpenSSLBadPassphraseError('Wrong or empty passphrase provided for private key')
            except ValueError as dummy:
                raise OpenSSLBadPassphraseError('Wrong passphrase provided for private key')

        return result
    except (IOError, OSError) as exc:
        raise OpenSSLObjectError(exc)
github openstack / python-tripleoclient / tripleoclient / v1 / undercloud_config.py View on Github external
def _get_public_tls_parameters(service_certificate_path):
    with open(service_certificate_path, "rb") as pem_file:
        pem_data = pem_file.read()
        cert = x509.load_pem_x509_certificate(pem_data, default_backend())
        private_key = serialization.load_pem_private_key(
            pem_data,
            password=None,
            backend=default_backend())

        key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption())
        cert_pem = cert.public_bytes(serialization.Encoding.PEM)
        return {
            'SSLCertificate': cert_pem,
            'SSLKey': key_pem
        }
github moepman / acertmgr / acertmgr / tools.py View on Github external
def read_pem_file(path, key=False, csr=False):
    with io.open(path, 'r') as f:
        if key:
            return serialization.load_pem_private_key(f.read().encode('utf-8'), None, default_backend())
        elif csr:
            return x509.load_pem_x509_csr(f.read().encode('utf8'), default_backend())
        else:
            return convert_pem_str_to_cert(f.read())
github woudt / bunq2ifttt / app / bunq.py View on Github external
del config[key]
    toload = storage.get_value("bunq2IFTTT", "bunq_config")
    if toload is not None:
        for key in toload:
            config[key] = toload[key]
    # Convert strings back to keys
    if "server_key_enc" in config:
        config["server_key"] = serialization.load_pem_public_key(
            config["server_key_enc"].encode("ascii"),
            backend=default_backend())
    if "public_key_enc" in config:
        config["public_key"] = serialization.load_pem_public_key(
            config["public_key_enc"].encode("ascii"),
            backend=default_backend())
    if "private_key_enc" in config:
        config["private_key"] = serialization.load_pem_private_key(
            config["private_key_enc"].encode("ascii"),
            password=None, backend=default_backend())
    return config
github crgwbr / asymmetric-jwt-auth / src / asymmetric_jwt_auth / __init__.py View on Github external
def decrypt_key(key, password):
    """
    Decrypt an encrypted private key.

    :param key: Encrypted private key as a string.
    :param password: Key pass-phrase.
    :return: Decrypted private key as a string.
    """
    private = serialization.load_pem_private_key(key, password=password, backend=default_backend())
    return private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())