Python OpenSSL.crypto.dump_certificate() Examples

The following are 30 code examples of OpenSSL.crypto.dump_certificate(). 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. You may also want to check out all available functions/classes of the module OpenSSL.crypto , or try the search function .
Example #1
Source File: publickey.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def pem_to_der_hex(self):
        """Convert PEM cert to DER format
        
        Converts PEM (Privacy Enhanced Mail) format to a hexadecimal 
        DER (Distinguished Encoding Rules) string.
        
        Returns:
            Chepy: The Chepy object.
        """
        cert_pem = _pyssl_crypto.load_certificate(
            _pyssl_crypto.FILETYPE_PEM, self.state
        )
        self.state = _pyssl_crypto.dump_certificate(
            _pyssl_crypto.FILETYPE_ASN1, cert_pem
        )
        return self 
Example #2
Source File: serving.py    From Financial-Portfolio-Flask with MIT License 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #3
Source File: publickey.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def dump_pkcs12_cert(self, password: str):
        """Get the private key and cert from pkcs12 cert
        
        Args:
            password (str): Password for certificate
        
        Returns:
            Chepy: The Chepy object. 
        """
        if isinstance(password, str):
            password = password.encode()
        pk12 = _pyssl_crypto.load_pkcs12(self._convert_to_bytes(), password)
        self.state = {
            "private": _pyssl_crypto.dump_privatekey(
                _pyssl_crypto.FILETYPE_PEM, pk12.get_privatekey()
            ),
            "cert": _pyssl_crypto.dump_certificate(
                _pyssl_crypto.FILETYPE_PEM, pk12.get_certificate()
            ),
        }
        return self 
Example #4
Source File: server.py    From Loki with MIT License 6 votes vote down vote up
def gen_cert(self):
        key_pair = crypto.PKey()
        key_pair.generate_key(crypto.TYPE_RSA, 2048)

        cert = crypto.X509()
        cert.get_subject().O = 'Loki'
        cert.get_subject().CN = 'Sami'
        cert.get_subject().OU = 'Pure-L0G1C'
        cert.get_subject().C = 'US'
        cert.get_subject().L = 'Los Santos'
        cert.get_subject().ST = 'California'

        cert.set_serial_number(SystemRandom().randint(2048 ** 8, 4096 ** 8))
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(256 * 409600)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key_pair)
        cert.sign(key_pair, 'sha256')

        with open(const.CERT_FILE, 'wb') as f:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))

        with open(const.KEY_FILE, 'wb') as f:
            f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair)) 
Example #5
Source File: createPemFiles.py    From devopsloft with GNU General Public License v3.0 6 votes vote down vote up
def SelfSignedCertificate():
    # create a key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)

    # create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = "IL"
    cert.get_subject().ST = "Jerusalem"
    cert.get_subject().L = "Jerusalem"
    cert.get_subject().OU = "DevOps Loft"
    cert.get_subject().CN = gethostname()
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha1')

    with open(CERT_FILE, "wb") as cert_f:
        cert_f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(KEY_FILE, "wb") as key_f:
        key_f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) 
Example #6
Source File: serving.py    From planespotter with MIT License 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #7
Source File: serving.py    From Flask-P2P with MIT License 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #8
Source File: turnserver.py    From aioice with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_self_signed_cert(name="localhost"):
    from OpenSSL import crypto

    # create key pair
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    # create self-signed certificate
    cert = crypto.X509()
    cert.get_subject().CN = name
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10 * 365 * 86400)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(key)
    cert.sign(key, "sha1")

    with open(CERT_FILE, "wb") as fp:
        fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(KEY_FILE, "wb") as fp:
        fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) 
Example #9
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_dump_certificate(self):
        """
        :py:obj:`dump_certificate` writes PEM, DER, and text.
        """
        pemData = cleartextCertificatePEM + cleartextPrivateKeyPEM
        cert = load_certificate(FILETYPE_PEM, pemData)
        dumped_pem = dump_certificate(FILETYPE_PEM, cert)
        self.assertEqual(dumped_pem, cleartextCertificatePEM)
        dumped_der = dump_certificate(FILETYPE_ASN1, cert)
        good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
        self.assertEqual(dumped_der, good_der)
        cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
        self.assertEqual(dumped_pem2, cleartextCertificatePEM)
        dumped_text = dump_certificate(FILETYPE_TEXT, cert)
        good_text = _runopenssl(dumped_pem, b"x509", b"-noout", b"-text")
        self.assertEqual(dumped_text, good_text) 
Example #10
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #11
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #12
Source File: ocsp_asn1crypto.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def extract_certificate_chain(self, connection):
        """Gets certificate chain and extract the key info from OpenSSL connection."""
        from OpenSSL.crypto import dump_certificate, FILETYPE_ASN1
        cert_map = OrderedDict()
        logger.debug(
            "# of certificates: %s",
            len(connection.get_peer_cert_chain()))

        for cert_openssl in connection.get_peer_cert_chain():
            cert_der = dump_certificate(FILETYPE_ASN1, cert_openssl)
            cert = Certificate.load(cert_der)
            logger.debug(
                'subject: %s, issuer: %s',
                cert.subject.native, cert.issuer.native)
            cert_map[cert.subject.sha256] = cert

        return self.create_pair_issuer_subject(cert_map) 
Example #13
Source File: ssl.py    From Exchange2domain with MIT License 6 votes vote down vote up
def generateImpacketCert(certname='/tmp/impacket.crt'):
    # Create a private key
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    # Create the certificate
    cert = crypto.X509()
    cert.gmtime_adj_notBefore(0)
    # Valid for 5 years
    cert.gmtime_adj_notAfter(60*60*24*365*5)
    subj = cert.get_subject()
    subj.CN = 'impacket'
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")
    # We write both from the same file
    with open(certname, 'w') as certfile:
        certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
        certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))
    LOG.debug('Wrote certificate to %s' % certname)

# Class to wrap the client socket in SSL when serving as a SOCKS server 
Example #14
Source File: authentication.py    From deskcon-desktop with GNU General Public License v3.0 6 votes vote down vote up
def generate_keypair(uuid):
    hostname = socket.gethostname()
    # create a key pair
    keypair = crypto.PKey()
    keypair.generate_key(crypto.TYPE_RSA, 2048)

    # create a self-signed cert
    cert = crypto.X509()
    cert.set_version(2)
    cert.get_subject().CN = str(uuid)+"/"+hostname
    cert.get_issuer().CN = str(uuid)+"/"+hostname
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_pubkey(keypair)
    cert.sign(keypair, 'sha256')

    certificate = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    privatekey = crypto.dump_privatekey(crypto.FILETYPE_PEM, keypair)
    return certificate, privatekey 
Example #15
Source File: serving.py    From scylla with Apache License 2.0 6 votes vote down vote up
def generate_adhoc_ssl_context():
    """Generates an adhoc SSL context for the development server."""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx 
Example #16
Source File: cms.py    From zentral with Apache License 2.0 5 votes vote down vote up
def verify_ca_issuer_openssl(ca_fullchain, certificate_bytes, strict=True):
    args = ["/usr/bin/openssl", "verify"]
    openssl_version = get_openssl_version()
    if not strict and openssl_version >= (1, 1):
        args.append("-no_check_time")
    args.extend(["-CAfile", ca_fullchain])
    p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, certificate_bytes)
    stdout, stderr = p.communicate(crypto.dump_certificate(crypto.FILETYPE_PEM, certificate))
    for line in stdout.splitlines():
        if strict and "error" in line.lower():
            return False
        if b'OK' in line:
            return True
    return False 
Example #17
Source File: ssl.py    From NintendoClients with MIT License 5 votes vote down vote up
def encode(self, format):
		return crypto.dump_certificate(TypeMap[format], self.obj) 
Example #18
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def make_ssl_devcert(base_path, host=None, cn=None):
    """Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    """
    from OpenSSL import crypto

    if host is not None:
        cn = "*.%s/CN=%s" % (host, host)
    cert, pkey = generate_adhoc_ssl_pair(cn=cn)

    cert_file = base_path + ".crt"
    pkey_file = base_path + ".key"

    with open(cert_file, "wb") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(pkey_file, "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))

    return cert_file, pkey_file 
Example #19
Source File: serving.py    From scylla with Apache License 2.0 5 votes vote down vote up
def make_ssl_devcert(base_path, host=None, cn=None):
    """Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    """
    from OpenSSL import crypto

    if host is not None:
        cn = "*.%s/CN=%s" % (host, host)
    cert, pkey = generate_adhoc_ssl_pair(cn=cn)

    cert_file = base_path + ".crt"
    pkey_file = base_path + ".key"

    with open(cert_file, "wb") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(pkey_file, "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))

    return cert_file, pkey_file 
Example #20
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def dump(self, format=crypto.FILETYPE_ASN1):
        return crypto.dump_certificate(format, self.original) 
Example #21
Source File: test_ssl.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateCertificateFiles(basename, organization, organizationalUnit):
    """
    Create certificate files key, req and cert prefixed by C{basename} for
    given C{organization} and C{organizationalUnit}.
    """
    pkey, req, cert = generateCertificateObjects(organization, organizationalUnit)

    for ext, obj, dumpFunc in [
        ('key', pkey, crypto.dump_privatekey),
        ('req', req, crypto.dump_certificate_request),
        ('cert', cert, crypto.dump_certificate)]:
        fName = os.extsep.join((basename, ext)).encode("utf-8")
        FilePath(fName).setContent(dumpFunc(crypto.FILETYPE_PEM, obj)) 
Example #22
Source File: man_cert_setup.py    From aws-greengrass-mini-fulfillment with Apache License 2.0 5 votes vote down vote up
def create_group_cert(cli):
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)  # generate RSA key-pair

    cert = crypto.X509()
    cert.get_subject().countryName = "US"
    cert.get_subject().stateOrProvinceName = "CA"
    cert.get_subject().organizationName = "mini-fulfillment"
    cert.get_subject().organizationalUnitName = "demo"
    cert.get_subject().commonName = "mini-fulfillment"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60)  # 5 year expiry date
    cert.set_issuer(cert.get_subject())  # self-sign this certificate
    cert.set_pubkey(k)
    san_list = ["IP:{0}".format(cli.ip_address)]
    extension_list = [
        crypto.X509Extension(type_name=b"basicConstraints",
                             critical=False, value=b"CA:false"),
        crypto.X509Extension(type_name=b"subjectAltName",
                             critical=True, value=", ".join(san_list)),
        # crypto.X509Extension(type_name=b"subjectKeyIdentifier",
        #                      critical=True, value=b"hash")
    ]
    cert.add_extensions(extension_list)
    cert.sign(k, 'sha256')

    prefix = str(cli.out_dir) + '/' + cli.group_name

    open("{0}-server.crt".format(prefix), 'wt').write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open("{0}-server-private.key".format(prefix), 'wt').write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey=k))
    open("{0}-server-public.key".format(prefix), 'wt').write(
        crypto.dump_publickey(crypto.FILETYPE_PEM, pkey=k)) 
Example #23
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def make_ssl_devcert(base_path, host=None, cn=None):
    """Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    """
    from OpenSSL import crypto

    if host is not None:
        cn = "*.%s/CN=%s" % (host, host)
    cert, pkey = generate_adhoc_ssl_pair(cn=cn)

    cert_file = base_path + ".crt"
    pkey_file = base_path + ".key"

    with open(cert_file, "wb") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(pkey_file, "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))

    return cert_file, pkey_file 
Example #24
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def dump(self, format=crypto.FILETYPE_ASN1):
        return crypto.dump_certificate(format, self.original) 
Example #25
Source File: getca.py    From satellite-demo with MIT License 5 votes vote down vote up
def printcert(host, port, hostname):
    con = Connection(Context(TLSv1_METHOD), socket(AF_INET, SOCK_STREAM))
    con.connect((host, port))
    con.set_tlsext_host_name(hostname if hostname else host)
    con.do_handshake()
    con.shutdown()
    con.close()
    print dump_certificate(FILETYPE_PEM, walkchain(con.get_peer_cert_chain())) 
Example #26
Source File: test_cert.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_x509_text(self):
        cert = self._create_cert()
        text = crypto.dump_certificate(crypto.FILETYPE_TEXT, cert.x509)
        self.assertEqual(cert.x509_text, text.decode('utf-8')) 
Example #27
Source File: pkcs12.py    From zentral with Apache License 2.0 5 votes vote down vote up
def load_push_certificate(pkcs12_bytes, password=None):
    args = [pkcs12_bytes]
    if password:
        if isinstance(password, str):
            password.encode("utf-8")
        args.append(password)
    pkcs12 = crypto.load_pkcs12(*args)
    certificate = pkcs12.get_certificate()
    private_key = pkcs12.get_privatekey()
    return {"certificate": crypto.dump_certificate(crypto.FILETYPE_PEM, certificate),
            "private_key": crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key),
            "not_before": parser.parse(certificate.get_notBefore()),
            "not_after": parser.parse(certificate.get_notAfter()),
            "topic": dict(certificate.get_subject().get_components())[b"UID"].decode("utf-8")} 
Example #28
Source File: serving.py    From Flask-P2P with MIT License 5 votes vote down vote up
def make_ssl_devcert(base_path, host=None, cn=None):
    """Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    """
    from OpenSSL import crypto
    if host is not None:
        cn = '*.%s/CN=%s' % (host, host)
    cert, pkey = generate_adhoc_ssl_pair(cn=cn)

    cert_file = base_path + '.crt'
    pkey_file = base_path + '.key'

    with open(cert_file, 'wb') as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(pkey_file, 'wb') as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))

    return cert_file, pkey_file 
Example #29
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def generateCertificateFiles(basename, organization, organizationalUnit):
    """
    Create certificate files key, req and cert prefixed by C{basename} for
    given C{organization} and C{organizationalUnit}.
    """
    pkey, req, cert = generateCertificateObjects(organization, organizationalUnit)

    for ext, obj, dumpFunc in [
        ('key', pkey, crypto.dump_privatekey),
        ('req', req, crypto.dump_certificate_request),
        ('cert', cert, crypto.dump_certificate)]:
        fName = os.extsep.join((basename, ext)).encode("utf-8")
        FilePath(fName).setContent(dumpFunc(crypto.FILETYPE_PEM, obj)) 
Example #30
Source File: dump_ocsp_response_cache.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def _fetch_certs(hostname_file):
    with open(hostname_file) as f:
        hostnames = f.read().split('\n')

    map_serial_to_name = {}
    for h in hostnames:
        if not h:
            continue
        connection = _openssl_connect(h, 443)
        for cert_openssl in connection.get_peer_cert_chain():
            cert_der = dump_certificate(FILETYPE_ASN1, cert_openssl)
            cert = Certificate.load(cert_der)
            map_serial_to_name[cert.serial_number] = cert.subject.native

    return map_serial_to_name