def certs(tmpdir_factory): dn = tmpdir_factory.mktemp("certs") k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) req = crypto.X509Req() subj = req.get_subject() subj.CN = "oskar1" req.set_pubkey(k) cert = crypto.X509() cert.set_serial_number(1) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10 * 24 * 60 * 60) # 10 days cert.set_issuer(subj) cert.set_subject(subj) cert.set_pubkey(k) cert.sign(k, "sha256") dn.join("oskar1.crt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert), ) subj.CN = "oskar2" cert.gmtime_adj_notAfter(20 * 24 * 60 * 60) # 20 days cert.set_issuer(subj) cert.set_subject(subj) cert.sign(k, "sha256") dn.join("oskar2.crt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert), ) subj.CN = "oskar3" cert.set_notAfter(b"20200220123456Z") cert.set_issuer(subj) cert.set_subject(subj) cert.sign(k, "sha256") dn.join("oskar3.crt").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert), ) return dn
def create_certificate_signing_request(cert_info): key = generate_key(cert_info['key_length']) req = crypto.X509Req() req.get_subject().C = cert_info['country'] req.get_subject().ST = cert_info['state'] req.get_subject().L = cert_info['city'] req.get_subject().O = cert_info['organization'] req.get_subject().CN = cert_info['common'] # first lets determine if an ip address was specified or # a dns entry in the common name default_san_type = 'DNS' try: ipaddress.ip_address(cert_info['common']) default_san_type = 'IP' except ValueError: # This is raised if say we specified freenas.org in the Common name pass if cert_info['san']: req.add_extensions([ crypto.X509Extension( b"subjectAltName", False, f"{default_san_type}:{cert_info['san']}".encode()) ]) req.get_subject().subjectAltName = cert_info['san'].replace(" ", ", ") req.get_subject().emailAddress = cert_info['email'] req.set_pubkey(key) sign_certificate(req, key, cert_info['digest_algorithm']) return (req, key)
def create_selfsigned_certificate(entityPrivKey, entityInfo, validForDays, serial=0, version=0, digest='sha1'): """ Create a self-signed certificate and return certificate (PEM, text, fingerprint). """ ekey = crypto.load_privatekey(crypto.FILETYPE_PEM, entityPrivKey) req = crypto.X509Req() subj = req.get_subject() fill_x509name_from_info(subj, entityInfo) req.set_pubkey(ekey) req.sign(ekey, digest) cert = crypto.X509() cert.set_serial_number(serial) cert.set_version(version) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * validForDays) cert.set_issuer(req.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(ekey, digest) certPem = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) certText = '???' certFingerprint = cert.digest(digest) return (certPem, certText, certFingerprint)
def get_csr(session_name, opt): # create CSR. csr = crypto.X509Req() subject = csr.get_subject() subject.CN = session_name.encode() # XXX the client's ip address should be set into SAN for RA's check ? # XXX currently, the address is set for sure. sans_list = [ "IP: {}".format(opt.client_addr).encode() ] x509_ext = [] x509_ext.append( crypto.X509Extension(type_name=b"subjectAltName", critical=False, value=b", ".join(sans_list))) csr.add_extensions(x509_ext) # generate a key pair and sign to CSR. pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, opt.key_size) csr.set_pubkey(pkey) csr.sign(pkey, "sha256") # save csr and key. csr_pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr) pkey_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey) return csr_pem, pkey_pem
def create_cert_request(p_key, digest="sha256", **subject_kwargs): """ Creates certificate request :param p_key: key to associate with the request :param digest: signing method :param subject_kwargs: subject of request valuable args are: (took from RFC 5280) C: country ST: state or province name L: Locality name O: organization OU: organizational unit CN: common name (e.g., "Susan Housley") emailAddress: e-mail :return: certificate request """ req = crypto.X509Req() subj = req.get_subject() for key, value in subject_kwargs.items(): setattr(subj, key, value) req.set_pubkey(p_key) req.sign(p_key, digest) return req
def make_csr(private_key_pem, domains, must_staple=False): """Generate a CSR containing a list of domains as subjectAltNames. :param buffer private_key_pem: Private key, in PEM PKCS#8 format. :param list domains: List of DNS names to include in subjectAltNames of CSR. :param bool must_staple: Whether to include the TLS Feature extension (aka OCSP Must Staple: https://tools.ietf.org/html/rfc7633). :returns: buffer PEM-encoded Certificate Signing Request. """ private_key = crypto.load_privatekey( crypto.FILETYPE_PEM, private_key_pem) csr = crypto.X509Req() extensions = [ crypto.X509Extension( b'subjectAltName', critical=False, value=', '.join('DNS:' + d for d in domains).encode('ascii') ), ] if must_staple: extensions.append(crypto.X509Extension( b"1.3.6.1.5.5.7.1.24", critical=False, value=b"DER:30:03:02:01:05")) csr.add_extensions(extensions) csr.set_pubkey(private_key) csr.set_version(2) csr.sign(private_key, 'sha256') return crypto.dump_certificate_request( crypto.FILETYPE_PEM, csr)
def generate_ssl_keys(): """ This method generates a new SSL key/cert. """ digest = "md5" # Generate key pair pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, 1024) # Generate cert request req = crypto.X509Req() subj = req.get_subject() setattr(subj, "CN", "Deluge Daemon") req.set_pubkey(pkey) req.sign(pkey, digest) # Generate certificate cert = crypto.X509() cert.set_serial_number(0) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5) # Five Years cert.set_issuer(req.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) cert.sign(pkey, digest) # Write out files ssl_dir = deluge.configmanager.get_config_dir("ssl") open(os.path.join(ssl_dir, "daemon.pkey"), "w").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)) open(os.path.join(ssl_dir, "daemon.cert"), "w").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) # Make the files only readable by this user for f in ("daemon.pkey", "daemon.cert"): os.chmod(os.path.join(ssl_dir, f), stat.S_IREAD | stat.S_IWRITE)
def run(self, certificate): try: certificate['key_length'] = certificate.get('key_length', 2048) certificate['digest_algorithm'] = certificate.get( 'digest_algorithm', 'SHA256') certificate['lifetime'] = certificate.get('lifetime', 3650) key = generate_key(certificate['key_length']) req = crypto.X509Req() req.get_subject().C = certificate['country'] req.get_subject().ST = certificate['state'] req.get_subject().L = certificate['city'] req.get_subject().O = certificate['organization'] req.get_subject().CN = certificate['common'] req.get_subject().emailAddress = certificate['email'] req.set_pubkey(key) req.sign(key, str(certificate['digest_algorithm'])) certificate['type'] = 'CERT_CSR' certificate['csr'] = crypto.dump_certificate_request( crypto.FILETYPE_PEM, req) certificate['privatekey'] = crypto.dump_privatekey( crypto.FILETYPE_PEM, key) pkey = self.datastore.insert('crypto.certificates', certificate) self.dispatcher.call_sync('etcd.generation.generate_group', 'crypto') except DatastoreException, e: raise TaskException(errno.EBADMSG, 'Cannot create CSR: {0}'.format(str(e)))
def create_certificate_signing_request(self, cert_info): cert_info['san'] = self.middleware.call_sync( 'certificate.san_to_string', cert_info.pop('san', [])) key = generate_key(cert_info['key_length']) req = crypto.X509Req() req.get_subject().C = cert_info['country'] req.get_subject().ST = cert_info['state'] req.get_subject().L = cert_info['city'] req.get_subject().O = cert_info['organization'] if cert_info.get('organizational_unit'): req.get_subject().OU = cert_info['organizational_unit'] req.get_subject().CN = cert_info['common'] if cert_info['san']: req.add_extensions([ crypto.X509Extension(b"subjectAltName", False, cert_info['san'].encode()) ]) req.get_subject().subjectAltName = cert_info['san'] req.get_subject().emailAddress = cert_info['email'] req.set_pubkey(key) req.sign(key, cert_info['digest_algorithm']) return (req, key)
def createCertRequest(pkey, **name): """ Create a certificate request. @param pkey: The key to associate with the request @type pkey: crypto.PKey @keyword 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 (always forced to be "Calathi project") OU - Organizational unit name CN - Common name emailAddress - E-mail address @returns: The certificate request in an X509Req object @rtype: crypto.X509Req """ req = crypto.X509Req() subj = req.get_subject() assert 'O' not in name, repr(name) for (key, value) in name.iteritems(): setattr(subj, key, value) setattr(subj, 'O', CERT_O) x = crypto.X509Extension('subjectAltName', True, 'otherName:1.2;UTF8:some other identifier') req.add_extensions([x]) req.set_pubkey(pkey) req.sign(pkey, OPENSSL_DIGEST) return req
def create_certreq(CN, keyPair, messageDigest=MESSAGE_DIGEST_TYPE): """Create a certificate request. @type CN: basestring @param CN: Common Name for certificate - effectively the same as the username for the MyProxy credential @type keyPair: string/None @param keyPair: public/private key pair @type messageDigest: basestring @param messageDigest: message digest type - default is MD5 @rtype: base string @return certificate request PEM text and private key PEM text """ # Check all required certificate request DN parameters are set # Create certificate request certReq = crypto.X509Req() # Create public key object certReq.set_pubkey(keyPair) # Add the public key to the request certReq.sign(keyPair, messageDigest) derCertReq = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, certReq) return derCertReq
def make_csr(pkey, CN, C=None, ST=None, L=None, O=None, OU=None, emailAddress=None, hashalgorithm='sha256WithRSAEncryption'): req = crypto.X509Req() req.get_subject() subj = req.get_subject() if C: subj.C = C if ST: subj.ST = ST if L: subj.L = L if O: subj.O = O if OU: subj.OU = OU if CN: subj.CN = CN if emailAddress: subj.emailAddress = emailAddress req.set_pubkey(pkey) req.sign(pkey, hashalgorithm) return req
def setup_atmcrypto(self): atmkey = crypto.PKey() atmkey.generate_key(crypto.TYPE_RSA, 2048) certreq = crypto.X509Req() certreq.get_subject().CN = "atm-machine.bank.example.com" certreq.set_pubkey(atmkey) certreq.sign(atmkey, "sha256") atmcert = crypto.X509() atmcert.set_subject(certreq.get_subject()) atmcert.set_serial_number(self._certauthoritynextserial) atmcert.set_issuer(self._certauthority.get_subject()) atmcert.gmtime_adj_notBefore(0) atmcert.gmtime_adj_notAfter(86400 * 365 * 3) # under CA's lifetime atmcert.set_pubkey(certreq.get_pubkey()) atmcert.add_extensions([ crypto.X509Extension("basicConstraints", True, "CA:FALSE"), crypto.X509ExtensionType("extendedKeyUsage", True, "clientAuth"), ]) atmcert.sign(self._certauthorityprivatekey, "sha256") self._certauthoritynextserial = self._certauthoritynextserial + 1 if path.exists(self._common_utils.get_authfilename()): self.error_exit('Auth file already exists (race check)') outfile = file(self._common_utils.get_authfilename(), 'w') outfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, atmkey)) outfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, atmcert)) outfile.write( crypto.dump_certificate(crypto.FILETYPE_PEM, self._certauthority)) outfile.close()
def generateCSR(nodename, cert_st, cert_loc, cert_org, cert_org_unit): """ # generates csr using ... # """ csrfile = nodename + '.csr' keyfile = nodename + '.key' TYPE_RSA = crypto.TYPE_RSA req = crypto.X509Req() req.get_subject().CN = nodename req.get_subject().countryName = "US" req.get_subject().stateOrProvinceName = cert_st req.get_subject().localityName = cert_loc req.get_subject().organizationName = cert_org req.get_subject().organizationalUnitName = cert_org_unit # Utilizes generateKey function to kick off key generation. key = generateKey(TYPE_RSA, 2048) req.set_pubkey(key) # hash/finger print is set to 256 and not "1" req.sign(key, "sha256") generateFiles(1, csrfile, req) generateFiles(2, keyfile, key) # later use of a flag return req
def generate(self): TYPE_RSA = crypto.TYPE_RSA req = crypto.X509Req() req = self.load_openssl_settigs(req) sans = [] for i in self.dns_names: sans.append("DNS: %s" % i) sans = ", ".join(sans) base_constraints = ([ crypto.X509Extension( b"keyUsage", False, b"Digital Signature, Non Repudiation, Key Encipherment"), crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"), ]) x509_extensions = base_constraints san_constraint = crypto.X509Extension(b"subjectAltName", False, sans.encode()) x509_extensions.append(san_constraint) req.add_extensions(x509_extensions) key = self.generateKey(TYPE_RSA, 2048) req.set_pubkey(key) req.sign(key, "sha1") return req, key
def createCertRequest(pkey, digest="sha256"): """ 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() req.get_subject().C = "FR" req.get_subject().ST = "IDF" req.get_subject().L = "Paris" req.get_subject().O = "RedHat" # noqa req.get_subject().OU = "DCI" req.get_subject().CN = "DCI-remoteCI" req.set_pubkey(pkey) req.sign(pkey, digest) return req
def _genPkeyCsr(self, name, mode, outp=None): pkey = crypto.PKey() pkey.generate_key(crypto.TYPE_RSA, self.crypto_numbits) xcsr = crypto.X509Req() xcsr.get_subject().CN = name xcsr.set_pubkey(pkey) xcsr.sign(pkey, self.signing_digest) keypath = self._savePkeyTo(pkey, mode, '%s.key' % name) if outp is not None: outp.printf('key saved: %s' % (keypath, )) csrpath = self._getPathJoin(mode, '%s.csr' % name) self._checkDupFile(csrpath) byts = crypto.dump_certificate_request(crypto.FILETYPE_PEM, xcsr) with s_common.genfile(csrpath) as fd: fd.truncate(0) fd.write(byts) if outp is not None: outp.printf('csr saved: %s' % (csrpath, )) return byts
def get_certificate(self, access_token): """ Generate a new key pair """ key_pair = crypto.PKey() key_pair.generate_key(crypto.TYPE_RSA, 2048) self.private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair).decode('utf-8') """ Generate a certificate request """ cert_request = crypto.X509Req() cert_request.set_pubkey(key_pair) cert_request.sign(key_pair, 'md5') cert_request = crypto.dump_certificate_request(crypto.FILETYPE_ASN1, cert_request) headers = {'Authorization': 'Bearer {}'.format(access_token)} url = self.CERTIFICATE_URL request_args = { 'headers': headers, 'data': { 'certificate_request': b64encode(cert_request) } } try: response = self.request(url, method='POST', **request_args) print response print response.text response.raise_for_status() except Exception, err: print Exception, err
def make_csr(pkey, dest=None, cn=None, hostname=None, emailaddr=None): req = crypto.X509Req() req.get_subject() subj = req.get_subject() subj.C = def_country subj.ST = def_state subj.L = def_local subj.O = def_org subj.OU = def_ou if cn: subj.CN = cn elif hostname: subj.CN = hostname else: subj.CN = utils.gethostname() if emailaddr: subj.emailAddress = emailaddr else: subj.emailAddress = 'root@%s' % subj.CN req.set_pubkey(pkey) req.sign(pkey, 'md5') if dest: destfd = os.open(dest, os.O_RDWR | os.O_CREAT, 0644) os.write(destfd, crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)) os.close(destfd) return req
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("subjectAltName", False, self.subjectAltName)]) 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, 'w') 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
def create_selfsigned_cert2(filename, user, key): """ Creates a self-signed cert with CN of issuer and subject = user. The file is stored in 'filename' and the public/private key is found in key """ from OpenSSL import crypto # Create a self-signed cert to talk to the registry with cert = crypto.X509() cert.set_serial_number(3) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(60*60*24*365*5) # five years req = crypto.X509Req() subj = req.get_subject() setattr(subj, "CN", user) cert.set_subject(subj) key = crypto.load_privatekey(crypto.FILETYPE_PEM, file(key).read()) cert.set_pubkey(key) cert.set_issuer(subj) cert.sign(key, "md5") f = open(filename,'w') f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) f.close()
def create_csr(common_name: str, country=None, state=None, city=None, organization=None, organizational_unit=None, email_address=None) -> (bytes, bytes): """ Returns: private key and certificate signing request (PEM). """ key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) req = crypto.X509Req() subject = req.get_subject() subject.CN = common_name if country: subject.C = country if state: subject.ST = state if city: subject.L = city if organization: subject.O = organization # noqa if organizational_unit: subject.OU = organizational_unit if email_address: subject.emailAddress = email_address req.set_pubkey(key) req.sign(key, 'sha256') return ( crypto.dump_privatekey(crypto.FILETYPE_PEM, key), crypto.dump_certificate_request(crypto.FILETYPE_PEM, req), )
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
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
def action_create_certificate_request(self): """ TODO agregar descripcion y ver si usamos pyafipsw para generar esto """ for record in self: req = crypto.X509Req() req.get_subject().C = self.country_id.code.encode( 'ascii', 'ignore') if self.state_id: req.get_subject().ST = self.state_id.name.encode( 'ascii', 'ignore') req.get_subject().L = self.city.encode( 'ascii', 'ignore') req.get_subject().O = self.company_id.name.encode( 'ascii', 'ignore') req.get_subject().OU = self.department.encode( 'ascii', 'ignore') req.get_subject().CN = self.common_name.encode( 'ascii', 'ignore') req.get_subject().serialNumber = 'CUIT %s' % self.cuit.encode( 'ascii', 'ignore') k = crypto.load_privatekey(crypto.FILETYPE_PEM, self.key) self.key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k) req.set_pubkey(k) req.sign(k, 'sha1') csr = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req) vals = { 'csr': csr, 'alias_id': record.id, } self.certificate_ids.create(vals) return True
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
def create_certificate_signing_request(subjectKey, subjectInfo, version=0, hash='sha1'): """ Create a certificate signing request (CSR) and return CSR in PEM and text formats. :param subjectKey: Subject private RSA key in PEM format. :type subjectKey: str :param subjectInfo: Subject information. :type subjectInfo: dict :returns tuple -- (CSR in PEM format, CSR as Text). """ skey = crypto.load_privatekey(crypto.FILETYPE_PEM, subjectKey) req = crypto.X509Req() subj = req.get_subject() fill_x509name_from_info(subj, subjectInfo) req.set_pubkey(skey) req.set_version(version) req.sign(skey, hash) csr_pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req) # FIXME: needs crypto.FILETYPE_TEXT csr_text = '???' return (csr_pem, csr_text)
def create_csr(CN=None, C=None, ST=None, L=None, O=None, OU=None): global key # generate key k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) # generate CSR req = crypto.X509Req() if CN: req.get_subject().CN = CN if C: req.get_subject().C = C if ST: req.get_subject().ST = ST if L: req.get_subject().L = L if O: req.get_subject().O = O if OU: req.get_subject().OU = OU req.set_pubkey(k) req.sign(k, "sha256") key = k # store their values private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, k) csr = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req) open("pkey.key", "wt").write(private_key.decode("utf-8")) open("req.csr", "wt").write(csr.decode("utf-8")) return private_key, csr
def create_cert_request(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
def generate_csr(customer_data, pkey_obj): from OpenSSL import crypto req = crypto.X509Req() req.get_subject().organizationName = customer_data.get('partner_name') req.get_subject().CN = '%s %s' % (customer_data.get('first_name'), customer_data.get('last_name')) req.get_subject().countryName = customer_data.get('country') req.get_subject().localityName = customer_data.get('city') req.get_subject().stateOrProvinceName = customer_data.get('state') req.get_subject().street = customer_data.get('street_address') req.get_subject().postalCode = customer_data.get('postal_code') base_constraints = ([ crypto.X509Extension( "keyUsage", False, "Digital Signature, Non Repudiation, Key Encipherment"), crypto.X509Extension("basicConstraints", False, "CA:FALSE") ]) req.add_extensions(base_constraints) req.set_pubkey(pkey_obj) req.sign(pkey_obj, 'sha256') return crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)