Python load pem

60 Python code examples are found related to " load pem". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: key.py    From baidupan_shell with GNU General Public License v2.0 7 votes vote down vote up
def load_pkcs1_openssl_pem(cls, keyfile):
        '''Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.
        
        These files can be recognised in that they start with BEGIN PUBLIC KEY
        rather than BEGIN RSA PUBLIC KEY.
        
        The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
        after the "-----END PUBLIC KEY-----" lines is ignored.

        @param keyfile: contents of a PEM-encoded file that contains the public
            key, from OpenSSL.
        @return: a PublicKey object
        '''

        der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
        return cls.load_pkcs1_openssl_der(der) 
Example 2
Source File: backend.py    From oss-ftp with MIT License 6 votes vote down vote up
def load_pem_public_key(self, data):
        mem_bio = self._bytes_to_bio(data)
        evp_pkey = self._lib.PEM_read_bio_PUBKEY(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if evp_pkey != self._ffi.NULL:
            evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
            return self._evp_pkey_to_public_key(evp_pkey)
        else:
            # It's not a (RSA/DSA/ECDSA) subjectPublicKeyInfo, but we still
            # need to check to see if it is a pure PKCS1 RSA public key (not
            # embedded in a subjectPublicKeyInfo)
            self._consume_errors()
            res = self._lib.BIO_reset(mem_bio.bio)
            self.openssl_assert(res == 1)
            rsa_cdata = self._lib.PEM_read_bio_RSAPublicKey(
                mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
            )
            if rsa_cdata != self._ffi.NULL:
                rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
                evp_pkey = self._rsa_cdata_to_evp_pkey(rsa_cdata)
                return _RSAPublicKey(self, rsa_cdata, evp_pkey)
            else:
                self._handle_key_loading_error() 
Example 3
Source File: key.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def load_pkcs1_openssl_pem(cls, keyfile):
        """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.

        These files can be recognised in that they start with BEGIN PUBLIC KEY
        rather than BEGIN RSA PUBLIC KEY.

        The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
        after the "-----END PUBLIC KEY-----" lines is ignored.

        :param keyfile: contents of a PEM-encoded file that contains the public
            key, from OpenSSL.
        :return: a PublicKey object
        """

        der = rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
        return cls.load_pkcs1_openssl_der(der) 
Example 4
Source File: key.py    From iot-core-micropython with Apache License 2.0 6 votes vote down vote up
def load_pkcs1_openssl_pem(cls, keyfile):
        """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.

        These files can be recognised in that they start with BEGIN PUBLIC KEY
        rather than BEGIN RSA PUBLIC KEY.

        The contents of the file before the "-----BEGIN PUBLIC KEY-----" and
        after the "-----END PUBLIC KEY-----" lines is ignored.

        :param keyfile: contents of a PEM-encoded file that contains the public
            key, from OpenSSL.
        :type keyfile: bytes
        :return: a PublicKey object
        """

        der = third_party.rsa.pem.load_pem(keyfile, 'PUBLIC KEY')
        return cls.load_pkcs1_openssl_der(der) 
Example 5
Source File: Tools.py    From joeecc with GNU General Public License v3.0 6 votes vote down vote up
def load_pem_data(filename, specifier):
	"""Loads the PEM payload, designated with a BEGIN and END specifier, from a
	file given by its filename."""
	data = None
	with open(filename, "r") as f:
		spec_begin = "-----BEGIN " + specifier + "-----"
		spec_end = "-----END " + specifier + "-----"
		for line in f:
			line = line.rstrip()
			if (data is None) and (line == spec_begin):
				data = [ ]
			elif (data is not None) and (line == spec_end):
				break
			elif data is not None:
				data.append(line)
	if data is None:
		raise Exception("Trying to parse PEM file with specifier '%s', but no such block in file found." % (specifier))
	data = base64.b64decode("".join(data).encode("utf-8"))
	return data 
Example 6
Source File: x509.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def load_pem_file(self, pem_file):
        """Load a PEM file. Returning `OpenSSL.crypto.X509` object and the
        contents of the file.

        :param pem_file: file to load
        """
        pem_data = read_text_file(pem_file)
        try:
            cert = OpenSSL.crypto.load_certificate(
                OpenSSL.crypto.FILETYPE_PEM, pem_data
            )
        except OpenSSL.crypto.Error as err:
            raise WinRMX509Error("Failed to load certificate: %s" % err)
        return cert, pem_data 
Example 7
Source File: backend.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_pem_parameters(self, data):
        mem_bio = self._bytes_to_bio(data)
        # only DH is supported currently
        dh_cdata = self._lib.PEM_read_bio_DHparams(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL)
        if dh_cdata != self._ffi.NULL:
            dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free)
            return _DHParameters(self, dh_cdata)
        else:
            self._handle_key_loading_error() 
Example 8
Source File: backend.py    From oss-ftp with MIT License 5 votes vote down vote up
def load_pem_x509_certificate(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509 = self._lib.PEM_read_bio_X509(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509 == self._ffi.NULL:
            self._consume_errors()
            raise ValueError("Unable to load certificate")

        x509 = self._ffi.gc(x509, self._lib.X509_free)
        return _Certificate(self, x509) 
Example 9
Source File: backend.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def load_pem_x509_certificate(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509 = self._lib.PEM_read_bio_X509(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509 == self._ffi.NULL:
            self._consume_errors()
            raise ValueError(
                "Unable to load certificate. See https://cryptography.io/en/la"
                "test/faq/#why-can-t-i-import-my-pem-file for more details."
            )

        x509 = self._ffi.gc(x509, self._lib.X509_free)
        return _Certificate(self, x509) 
Example 10
Source File: cryptolib.py    From confidant with Apache License 2.0 5 votes vote down vote up
def load_x509_certificate_pem_as_bare_base64(path):
    """
    Load an X.509 PEM certificate from a file, return as bare base64-encoded
    DER.

    :param path: The file path to an X.509 certificate in PEM format.
    :type path: string

    :returns: base64-encoded DER X.509 data.
    :rtype: string
    """
    return _x509_certificate_bare_base64(
        load_x509_certificate_pem(path)) 
Example 11
Source File: cryptolib.py    From confidant with Apache License 2.0 5 votes vote down vote up
def load_private_key_pem(path, password=None):
    """
    Load an RSA private key from a file.

    :param path: The file path to an RSA private key in PEM format.
    :type path: string

    :param password: A password encrypting the file.
    :type password: string

    :returns: An RSA private key object.
    :rtype: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
    """
    with open(path, 'rb') as f:
        return serialization.load_pem_private_key(f.read(), password=password,
                                                  backend=default_backend()) 
Example 12
Source File: cryptolib.py    From confidant with Apache License 2.0 5 votes vote down vote up
def load_x509_certificate_pem(path):
    """
    Load an X.509 PEM certificate from a file.

    :param path: The file path to an X.509 certificate in PEM format.
    :type path: string

    :returns: X.509 certificate object
    :rtype: cryptography.x509.Certificate
    """

    with open(path, 'rb') as f:
        cert = x509.load_pem_x509_certificate(f.read(), default_backend())
        return cert 
Example 13
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def loadPEM(Class, data):
        """
        Load a certificate from a PEM-format data string.

        @rtype: C{Class}
        """
        return Class.load(data, crypto.FILETYPE_PEM) 
Example 14
Source File: backend.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def load_pem_x509_csr(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509_req = self._lib.PEM_read_bio_X509_REQ(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509_req == self._ffi.NULL:
            self._consume_errors()
            raise ValueError("Unable to load request")

        x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
        return _CertificateSigningRequest(self, x509_req) 
Example 15
Source File: backend.py    From quickstart-git2s3 with Apache License 2.0 5 votes vote down vote up
def load_pem_x509_crl(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509_crl = self._lib.PEM_read_bio_X509_CRL(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509_crl == self._ffi.NULL:
            self._consume_errors()
            raise ValueError("Unable to load CRL")

        x509_crl = self._ffi.gc(x509_crl, self._lib.X509_CRL_free)
        return _CertificateRevocationList(self, x509_crl) 
Example 16
Source File: backend.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def load_pem_x509_crl(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509_crl = self._lib.PEM_read_bio_X509_CRL(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509_crl == self._ffi.NULL:
            self._consume_errors()
            raise ValueError(
                "Unable to load CRL. See https://cryptography.io/en/la"
                "test/faq/#why-can-t-i-import-my-pem-file for more details."
            )

        x509_crl = self._ffi.gc(x509_crl, self._lib.X509_CRL_free)
        return _CertificateRevocationList(self, x509_crl) 
Example 17
Source File: backend.py    From quickstart-redhat-openshift with Apache License 2.0 5 votes vote down vote up
def load_pem_x509_csr(self, data):
        mem_bio = self._bytes_to_bio(data)
        x509_req = self._lib.PEM_read_bio_X509_REQ(
            mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL
        )
        if x509_req == self._ffi.NULL:
            self._consume_errors()
            raise ValueError(
                "Unable to load request. See https://cryptography.io/en/la"
                "test/faq/#why-can-t-i-import-my-pem-file for more details."
            )

        x509_req = self._ffi.gc(x509_req, self._lib.X509_REQ_free)
        return _CertificateSigningRequest(self, x509_req) 
Example 18
Source File: cert_manager.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_pem(
        self, entity_type=None, path=None, pem_text=None, password=None
    ):
        """ Load pem encoded entity

        Attributes:
            entity_type (str): certificate|key|csr.
            path (str): Absolute path to file containing pem encoded entity.
            pem_text (str): String object with pem encoded entity
            password (str): Password to use in case entity is protected
        """
        if path and pem_text:
            raise ValueError("Path and pem_text are mutually exclusive")

        if path:
            with open(path, "rb") as f:
                pem_text = f.read()

        if entity_type == "certificate":
            return load_pem_x509_certificate(
                pem_text, backend=default_backend()
            )
        elif entity_type == "csr":
            return load_pem_x509_csr(pem_text, backend=default_backend())
        elif entity_type == "key":
            return load_pem_private_key(
                pem_text, password=password, backend=default_backend(),
            )
        else:
            raise ValueError("Unsupported entity_type {}".format(entity_type)) 
Example 19
Source File: crypto.py    From manuale with MIT License 5 votes vote down vote up
def load_pem_certificate(data):
    """
    Loads a PEM X.509 certificate.
    """
    return x509.load_pem_x509_certificate(data, default_backend()) 
Example 20
Source File: interfaces.py    From quickstart-redhat-openshift with Apache License 2.0 4 votes vote down vote up
def load_pem_private_key(self, data, password):
        """
        Loads a private key from PEM encoded data, using the provided password
        if the data is encrypted.
        """ 
Example 21
Source File: pem.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def load_pem(contents, pem_marker):
    """Loads a PEM file.

    :param contents: the contents of the file to interpret
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-decoded content between the start and end markers.

    @raise ValueError: when the content is invalid, for example when the start
        marker cannot be found.

    """

    # We want bytes, not text. If it's text, it can be converted to ASCII bytes.
    if not is_bytes(contents):
        contents = contents.encode('ascii')

    (pem_start, pem_end) = _markers(pem_marker)

    pem_lines = []
    in_pem_part = False

    for line in contents.splitlines():
        line = line.strip()

        # Skip empty lines
        if not line:
            continue

        # Handle start marker
        if line == pem_start:
            if in_pem_part:
                raise ValueError('Seen start marker "%s" twice' % pem_start)

            in_pem_part = True
            continue

        # Skip stuff before first marker
        if not in_pem_part:
            continue

        # Handle end marker
        if in_pem_part and line == pem_end:
            in_pem_part = False
            break

        # Load fields
        if b(':') in line:
            continue

        pem_lines.append(line)

    # Do some sanity checks
    if not pem_lines:
        raise ValueError('No PEM start marker "%s" found' % pem_start)

    if in_pem_part:
        raise ValueError('No PEM end marker "%s" found' % pem_end)

    # Base64-decode the contents
    pem = b('').join(pem_lines)
    return base64.standard_b64decode(pem) 
Example 22
Source File: tls.py    From dcos-e2e with Apache License 2.0 4 votes vote down vote up
def load_pem_x509_cert(cert_pem, allow_ec_cert=True):
    """
    Load X.509 certificate from the provided PEM/text representation.

    - Expect a single X.509 certificate in the "OpenSSL PEM format"
      (see https://tools.ietf.org/html/rfc7468#section-5 for format
      specification).

    - Expect that the public key of the certificate is of type RSA or EC
      (if enabled via allow_ec_cert).

    Note that if the certificate text representations contains more than one
    certificate definition, x509.load_pem_x509_certificate would silently read
    only the first one.


    Args:
        cert_pem (str): the PEM text representation of the data to verify.
        allow_ec_cert (bool): True if EC public key is supported.

    Returns:
        `cert`, an object of type `cryptography.x509.Certificate`.

    Raises:
        CertValidationError
    """

    if cert_pem.count('BEGIN CERTIFICATE') > 1:
        raise CertValidationError(
            'Certificate data contains more than one certificate definition.')

    try:
        cert = x509.load_pem_x509_certificate(
            data=cert_pem.encode('utf-8'),
            backend=cryptography_default_backend
            )
    except ValueError as e:
        raise CertValidationError('Invalid certificate: %s' % e)

    public_key = cert.public_key()

    supported_keys = OrderedDict([(rsa.RSAPublicKey, 'RSA')])
    if allow_ec_cert:
        supported_keys[ec.EllipticCurvePublicKey] = 'EC'

    if not isinstance(public_key, tuple(supported_keys.keys())):
        names = list(supported_keys.values())
        if len(names) > 1:
            names_str = ', '.join(names[:-1]) + ' or ' + names[-1]
        else:
            names_str = names[0]

        raise CertValidationError(
            'Unexpected public key type (not {})'.format(names_str))

    return cert