Python OpenSSL.crypto.dump_certificate_request() Examples

The following are 30 code examples of OpenSSL.crypto.dump_certificate_request(). 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: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_dump_certificate_request(self):
        """
        :py:obj:`dump_certificate_request` writes a PEM, DER, and text.
        """
        req = load_certificate_request(FILETYPE_PEM, cleartextCertificateRequestPEM)
        dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
        self.assertEqual(dumped_pem, cleartextCertificateRequestPEM)
        dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
        good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
        self.assertEqual(dumped_der, good_der)
        req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
        self.assertEqual(dumped_pem2, cleartextCertificateRequestPEM)
        dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
        good_text = _runopenssl(dumped_pem, b"req", b"-noout", b"-text")
        self.assertEqual(dumped_text, good_text)
        self.assertRaises(ValueError, dump_certificate_request, 100, req) 
Example #2
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_dump_certificate_request(self):
        """
        `dump_certificate_request` writes a PEM, DER, and text.
        """
        req = load_certificate_request(
            FILETYPE_PEM, cleartextCertificateRequestPEM)
        dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
        assert dumped_pem == cleartextCertificateRequestPEM
        dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
        good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
        assert dumped_der == good_der
        req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
        dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
        assert dumped_pem2 == cleartextCertificateRequestPEM
        dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
        good_text = _runopenssl(
            dumped_pem, b"req", b"-noout", b"-text", b"-nameopt", b"")
        assert dumped_text == good_text
        with pytest.raises(ValueError):
            dump_certificate_request(100, req) 
Example #3
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #4
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_request(format, self.original) 
Example #5
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #6
Source File: openssl_csr.py    From Ansible with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(b"subjectAltName", False, self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #7
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def dump(self, format=crypto.FILETYPE_ASN1):
        return crypto.dump_certificate_request(format, self.original) 
Example #8
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, osslpkey):
        self.original = osslpkey
        req1 = crypto.X509Req()
        req1.set_pubkey(osslpkey)
        self._emptyReq = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, req1) 
Example #9
Source File: test_ssl.py    From python-for-android with Apache License 2.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))
        fObj = file(fName, 'w')
        fObj.write(dumpFunc(crypto.FILETYPE_PEM, obj))
        fObj.close() 
Example #10
Source File: test_snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def test_issue_certificate_request(self):
        req = certificate_utils.get_valid_csr_object()

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        req_enc = base64.b64encode(req_enc)
        order_meta = {'request_data': req_enc}
        resp = self.plugin.issue_certificate_request(self.order_id,
                                                     order_meta, {},
                                                     self.barbican_meta_dto)
        crypto.load_certificate(
            crypto.FILETYPE_PEM, base64.b64decode(resp.certificate)) 
Example #11
Source File: test_snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def test_issue_certificate_request_with_ca_id(self):
        req = certificate_utils.get_valid_csr_object()

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        req_enc = base64.b64encode(req_enc)
        order_meta = {'request_data': req_enc}
        plugin_meta = {'plugin_ca_id': self.plugin.get_default_ca_name()}
        self.barbican_meta_dto.plugin_ca_id = self.plugin.get_default_ca_name()
        resp = self.plugin.issue_certificate_request(self.order_id,
                                                     order_meta,
                                                     plugin_meta,
                                                     self.barbican_meta_dto)
        crypto.load_certificate(
            crypto.FILETYPE_PEM, base64.b64decode(resp.certificate)) 
Example #12
Source File: test_snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def test_issue_raises_with_invalid_ca_id(self):
        req = certificate_utils.get_valid_csr_object()

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        req_enc = base64.b64encode(req_enc)
        order_meta = {'request_data': req_enc}
        plugin_meta = {'plugin_ca_id': "invalid_ca_id"}
        self.barbican_meta_dto.plugin_ca_id = "invalid_ca_id"
        self.assertRaises(
            cm.CertificateGeneralException,
            self.plugin.issue_certificate_request,
            self.order_id,
            order_meta,
            plugin_meta,
            self.barbican_meta_dto) 
Example #13
Source File: test_snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def test_issue_certificate_request_set_subject(self):
        req = certificate_utils.get_valid_csr_object()

        subj = req.get_subject()
        subj.countryName = 'US'
        subj.stateOrProvinceName = 'OR'
        subj.localityName = 'Testlandia'
        subj.organizationName = 'Testers Anon'
        subj.organizationalUnitName = 'Testers OU'
        subj.commonName = 'Testing'

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        req_enc = base64.b64encode(req_enc)
        order_meta = {'request_data': req_enc}
        resp = self.plugin.issue_certificate_request(self.order_id,
                                                     order_meta, {},
                                                     self.barbican_meta_dto)
        cert = crypto.load_certificate(
            crypto.FILETYPE_PEM, base64.b64decode(resp.certificate))
        cert_subj = cert.get_subject()
        self.assertEqual('US', cert_subj.C)
        self.assertEqual('OR', cert_subj.ST)
        self.assertEqual('Testlandia', cert_subj.L)
        self.assertEqual('Testers Anon', cert_subj.O)
        self.assertEqual('Testers OU', cert_subj.OU)
        self.assertEqual('Testing', cert_subj.CN) 
Example #14
Source File: test_snakeoil_ca.py    From barbican with Apache License 2.0 5 votes vote down vote up
def test_issue_certificate_request_stored_key(self):
        req = certificate_utils.get_valid_csr_object()

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        self.barbican_meta_dto.generated_csr = req_enc
        resp = self.plugin.issue_certificate_request(
            self.order_id, {}, {}, self.barbican_meta_dto)
        crypto.load_certificate(
            crypto.FILETYPE_PEM, base64.b64decode(resp.certificate)) 
Example #15
Source File: certificate_utils.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_good_csr():
    """Generate a CSR that will pass validation."""
    csr = get_valid_csr_object()
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #16
Source File: certificate_utils.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_csr_that_has_not_been_signed():
    """Generate a CSR that has not been signed."""
    key_pair = create_key_pair(crypto.TYPE_RSA, 2048)
    csr = crypto.X509Req()
    subject = csr.get_subject()
    setattr(subject, "CN", "host.example.net")
    csr.set_pubkey(key_pair)
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #17
Source File: certificate_utils.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_csr_signed_with_wrong_key():
    """Generate a CSR that has been signed by the wrong key."""
    key_pair1 = create_key_pair(crypto.TYPE_RSA, 2048)
    key_pair2 = create_key_pair(crypto.TYPE_RSA, 2048)
    csr = crypto.X509Req()
    subject = csr.get_subject()
    setattr(subject, "CN", "host.example.net")
    # set public key from key pair 1
    csr.set_pubkey(key_pair1)
    # sign with public key from key pair 2
    csr.sign(key_pair2, "sha256")
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #18
Source File: certificate_utils.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_csr_with_bad_subject_dn():
    """Generate a CSR that has a bad subject dn."""
    key_pair = create_key_pair(crypto.TYPE_RSA, 2048)
    csr = crypto.X509Req()
    subject = csr.get_subject()
    # server certs require attribute 'CN'
    setattr(subject, "UID", "bar")
    csr.set_pubkey(key_pair)
    csr.sign(key_pair, "sha256")
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #19
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def generateCertificateFiles(basename, organization, 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))
        fObj = file(fName, 'w')
        fObj.write(dumpFunc(crypto.FILETYPE_PEM, obj))
        fObj.close() 
Example #20
Source File: openssl_csr.py    From docket with Apache License 2.0 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not self.check(module, perms_required=False) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            altnames = ', '.join(self.subjectAltName)
            extensions = [crypto.X509Extension(b"subjectAltName", False, altnames.encode('ascii'))]

            if self.keyUsage:
                usages = ', '.join(self.keyUsage)
                extensions.append(crypto.X509Extension(b"keyUsage", False, usages.encode('ascii')))

            if self.extendedKeyUsage:
                usages = ', '.join(self.extendedKeyUsage)
                extensions.append(crypto.X509Extension(b"extendedKeyUsage", False, usages.encode('ascii')))

            req.add_extensions(extensions)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)

            self.changed = True

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #21
Source File: certificate_utils.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def create_csr_signed_with_wrong_key():
    """Generate a CSR that has been signed by the wrong key."""
    key_pair1 = create_key_pair(crypto.TYPE_RSA, 2048)
    key_pair2 = create_key_pair(crypto.TYPE_RSA, 2048)
    csr = crypto.X509Req()
    subject = csr.get_subject()
    setattr(subject, "CN", "host.example.net")
    # set public key from key pair 1
    csr.set_pubkey(key_pair1)
    # sign with public key from key pair 2
    csr.sign(key_pair2, "sha256")
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #22
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 #23
Source File: certs.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def emit(self, fo, filetype="pem"):
        fo.write(crypto.dump_certificate_request(_FILETYPES[filetype],
                 self._req)) 
Example #24
Source File: certs.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def get_pem(self):
        return crypto.dump_certificate_request(crypto.FILETYPE_PEM, self._req) 
Example #25
Source File: openssl_csr.py    From ansible-nginx-load-balancer with MIT License 5 votes vote down vote up
def generate(self, module):
        '''Generate the certificate signing request.'''

        if not os.path.exists(self.path) or self.force:
            req = crypto.X509Req()
            req.set_version(self.version)
            subject = req.get_subject()
            for (key, value) in self.subject.items():
                if value is not None:
                    setattr(subject, key, value)

            if self.subjectAltName is not None:
                req.add_extensions([crypto.X509Extension(
                    b"subjectAltName", False,
                    self.subjectAltName.encode('ascii'))])

            privatekey_content = open(self.privatekey_path).read()
            self.privatekey = crypto.load_privatekey(
                crypto.FILETYPE_PEM, privatekey_content)

            req.set_pubkey(self.privatekey)
            req.sign(self.privatekey, self.digest)
            self.request = req

            try:
                csr_file = open(self.path, 'wb')
                csr_file.write(crypto.dump_certificate_request(
                    crypto.FILETYPE_PEM, self.request))
                csr_file.close()
            except (IOError, OSError) as exc:
                raise CertificateSigningRequestError(exc)
        else:
            self.changed = False

        file_args = module.load_file_common_arguments(module.params)
        if module.set_fs_attributes_if_different(file_args, False):
            self.changed = True 
Example #26
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_request(format, self.original) 
Example #27
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 #28
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #29
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #30
Source File: test_snakeoil_ca.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_issue_certificate_request(self):
        req = certificate_utils.get_valid_csr_object()

        req_enc = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
        req_enc = base64.b64encode(req_enc)
        order_meta = {'request_data': req_enc}
        resp = self.plugin.issue_certificate_request(self.order_id,
                                                     order_meta, {},
                                                     self.barbican_meta_dto)
        crypto.load_certificate(
            crypto.FILETYPE_PEM, resp.certificate.decode('base64'))