Python OpenSSL.crypto.X509Req() Examples

The following are 30 code examples of OpenSSL.crypto.X509Req(). 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: Tbon.py    From pcocc with GNU General Public License v3.0 7 votes vote down vote up
def createCertRequest(pkey, digest="md5", **name):
    """
    Create a certificate request.
    Arguments: pkey   - The key to associate with the request
               digest - Digestion method to use for signing, default is md5
               **name - The name of the subject of the request, possible
                        arguments are:
                          C     - Country name
                          ST    - State or province name
                          L     - Locality name
                          O     - Organization name
                          OU    - Organizational unit name
                          CN    - Common name
                          emailAddress - E-mail address
    Returns:   The certificate request in an X509Req object
    """
    req = crypto.X509Req()
    subj = req.get_subject()

    for (key,value) in name.items():
        setattr(subj, key, value)

    req.set_pubkey(pkey)
    req.sign(pkey, digest)
    return req 
Example #2
Source File: certgen.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def createCertRequest(pkey, digest="sha256", **name):
    """
    Create a certificate request.
    Arguments: pkey   - The key to associate with the request
               digest - Digestion method to use for signing, default is sha256
               **name - The name of the subject of the request, possible
                        arguments are:
                          C     - Country name
                          ST    - State or province name
                          L     - Locality name
                          O     - Organization name
                          OU    - Organizational unit name
                          CN    - Common name
                          emailAddress - E-mail address
    Returns:   The certificate request in an X509Req object
    """
    req = crypto.X509Req()
    subj = req.get_subject()

    for key, value in name.items():
        setattr(subj, key, value)

    req.set_pubkey(pkey)
    req.sign(pkey, digest)
    return req 
Example #3
Source File: certs.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def __init__(self, country=None, state=None, locality=None,
                 organization=None, organization_unit=None,
                 name=None, email=None, digest="sha1", filename=None):
        if filename is None:
            req = crypto.X509Req()
            subject = req.get_subject()
            if country:
                subject.C = country
            if state:
                subject.ST = state
            if locality:
                subject.L = locality
            if organization:
                subject.O = organization
            if organization_unit:
                subject.OU = organization_unit
            if name:
                subject.CN = name
            if email:
                subject.emailAddress = email
        else:
            ftype, text = get_type_and_text(filename)
            req = crypto.load_certificate_request(ftype, text)
        self._req = req 
Example #4
Source File: certs.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def __init__(self, country=None, state=None, locality=None,
                 organization=None, organization_unit=None,
                 name=None, email=None, _dn=None):
        if _dn is None:
            dn = crypto.X509Req().get_subject()
            if country:
                dn.C = country
            if state:
                dn.ST = state
            if locality:
                dn.L = locality
            if organization:
                dn.O = organization
            if organization_unit:
                dn.OU = organization_unit
            if name:
                dn.CN = name
            if email:
                dn.emailAddress = email
        else:
            dn = _dn
        self.__dict__["_dn"] = dn 
Example #5
Source File: generate-certificates.py    From mpyc with MIT License 6 votes vote down vote up
def create_request(pk, common_name):
    """Create a certificate request."""
    rq = crypto.X509Req()
    subj = rq.get_subject()
    subj.CN = common_name
    rq.set_pubkey(pk)
    rq.sign(pk, 'sha256')
    return rq 
Example #6
Source File: test_ssl.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def generateCertificateObjects(organization, organizationalUnit):
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 512)
    req = crypto.X509Req()
    subject = req.get_subject()
    subject.O = organization
    subject.OU = organizationalUnit
    req.set_pubkey(pkey)
    req.sign(pkey, "md5")

    # Here comes the actual certificate
    cert = crypto.X509()
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
    cert.set_issuer(req.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.sign(pkey, "md5")

    return pkey, req, cert 
Example #7
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 #8
Source File: _sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def requestObject(self, distinguishedName, digestAlgorithm='sha256'):
        req = crypto.X509Req()
        req.set_pubkey(self.original)
        distinguishedName._copyInto(req.get_subject())
        req.sign(self.original, digestAlgorithm)
        return CertificateRequest(req) 
Example #9
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 #10
Source File: _sslverify.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def requestObject(self, distinguishedName, digestAlgorithm='md5'):
        req = crypto.X509Req()
        req.set_pubkey(self.original)
        distinguishedName._copyInto(req.get_subject())
        req.sign(self.original, digestAlgorithm)
        return CertificateRequest(req) 
Example #11
Source File: test_ssl.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def generateCertificateObjects(organization, organizationalUnit):
    """
    Create a certificate for given C{organization} and C{organizationalUnit}.

    @return: a tuple of (key, request, certificate) objects.
    """
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 512)
    req = crypto.X509Req()
    subject = req.get_subject()
    subject.O = organization
    subject.OU = organizationalUnit
    req.set_pubkey(pkey)
    req.sign(pkey, "md5")

    # Here comes the actual certificate
    cert = crypto.X509()
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
    cert.set_issuer(req.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.sign(pkey, "md5")

    return pkey, req, cert 
Example #12
Source File: certificate_utils.py    From barbican with Apache License 2.0 5 votes vote down vote up
def get_valid_csr_object():
    """Create a valid X509Req object"""
    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)
    csr.sign(key_pair, "sha256")
    return csr 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: generate.py    From openvpn-rapid-config with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_certificate(config_cert, ca, cakey, name):
    # Generate the private key
    key = openssl_generate_privatekey(config_cert['keyfilesize'])

    # Generate the certificate request
    req = crypto.X509Req()
    req_subj = req.get_subject()
    if 'commonName' in config_cert:
        req_subj.commonName = config_cert['commonName']
    if 'stateOrProvinceName' in config_cert:
        req_subj.stateOrProvinceName = config_cert['stateOrProvinceName']
    if 'localityName' in config_cert:
        req_subj.localityName = config_cert['localityName']
    if 'organizationName' in config_cert:
        req_subj.organizationName = config_cert['organizationName']
    if 'organizationalUnitName' in config_cert:
        req_subj.organizationalUnitName = config_cert['organizationalUnitName']
    if 'emailAddress' in config_cert:
        req_subj.emailAddress = config_cert['emailAddress']
    if 'countryName' in config_cert:
        req_subj.countryName = config_cert['countryName']

    req.set_pubkey(key)
    req.sign(key, config_cert['hashalgorithm'])

    # Now generate the certificate itself
    cert = crypto.X509()
    cert.set_version(2)
    cert.set_serial_number(config_cert['serial'])
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.set_issuer(ca.get_subject())

    if 'validfrom' in config_cert:
        cert.set_notBefore(config_cert['validfrom'])
    if 'validto' in config_cert:
        cert.set_notAfter(config_cert['validto'])

    if name == 'client':
        usage = 'clientAuth'
        nscerttype = 'client'
    elif name == 'server':
        usage = 'serverAuth'
        nscerttype = 'server'
    else:
        sys.stdout.write("ERROR: Bad certificate type\n")
        sys.exit(1)

    cert.add_extensions([
        crypto.X509Extension("basicConstraints", True, "CA:FALSE"),
        crypto.X509Extension("keyUsage", False, "digitalSignature,keyAgreement"),
        crypto.X509Extension("extendedKeyUsage", False, usage),
        crypto.X509Extension("nsCertType", False, nscerttype),
        crypto.X509Extension("subjectKeyIdentifier", False, "hash", subject=cert),
        crypto.X509Extension("authorityKeyIdentifier", False, "keyid:always", issuer=ca)
    ])

    cert.sign(cakey, config_cert['hashalgorithm'])
    return req, cert, key 
Example #18
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 #19
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 #20
Source File: certificate_utils.py    From sgx-kms 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 #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: certificate_utils.py    From sgx-kms 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 #23
Source File: certificate_utils.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def get_valid_csr_object():
    """Create a valid X509Req object"""
    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)
    csr.sign(key_pair, "sha256")
    return csr 
Example #24
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 #25
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 #26
Source File: test_ssl.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateCertificateObjects(organization, organizationalUnit):
    """
    Create a certificate for given C{organization} and C{organizationalUnit}.

    @return: a tuple of (key, request, certificate) objects.
    """
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 1024)
    req = crypto.X509Req()
    subject = req.get_subject()
    subject.O = organization
    subject.OU = organizationalUnit
    req.set_pubkey(pkey)
    req.sign(pkey, "md5")

    # Here comes the actual certificate
    cert = crypto.X509()
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
    cert.set_issuer(req.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.sign(pkey, "md5")

    return pkey, req, cert 
Example #27
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def requestObject(self, distinguishedName, digestAlgorithm='sha256'):
        req = crypto.X509Req()
        req.set_pubkey(self.original)
        distinguishedName._copyInto(req.get_subject())
        req.sign(self.original, digestAlgorithm)
        return CertificateRequest(req) 
Example #28
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 #29
Source File: test_ssl.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def generateCertificateObjects(organization, organizationalUnit):
    """
    Create a certificate for given C{organization} and C{organizationalUnit}.

    @return: a tuple of (key, request, certificate) objects.
    """
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 512)
    req = crypto.X509Req()
    subject = req.get_subject()
    subject.O = organization
    subject.OU = organizationalUnit
    req.set_pubkey(pkey)
    req.sign(pkey, "md5")

    # Here comes the actual certificate
    cert = crypto.X509()
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
    cert.set_issuer(req.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.sign(pkey, "md5")

    return pkey, req, cert 
Example #30
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 4 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