def generate_cert_key_pair(self): private_key = EVP.PKey() rsa = M2RSA.gen_key(2048, 65537, lambda: None) private_key.assign_rsa(rsa) req = X509.Request() req.set_pubkey(private_key) name = req.get_subject() name.CN = 'NVIDIA GameStream Client' req.sign(private_key, 'sha1') public_key = req.get_pubkey() cert = X509.X509() cert.set_serial_number(1) cert.set_version(2) self.validate_cert(cert) cert.set_issuer(name) cert.set_subject(cert.get_issuer()) cert.set_pubkey(public_key) cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE', 1)) cert.add_ext(X509.new_extension('keyUsage', 'keyCertSign, cRLSign', 1)) cert.add_ext( X509.new_extension('subjectKeyIdentifier', cert.get_fingerprint())) cert.sign(private_key, 'sha1') cert.save(self.cert_file, 1) with open(self.key_file, 'wb') as key_file: key_file.write(private_key.as_pem(None)) key_file.close() self.load_cert_key_pair()
def make_csr(key_file, domains): """ Returns new CSR in PEM and DER form using key_file containing all domains """ assert domains, "Must provide one or more hostnames for the CSR." rsa_key = M2Crypto.RSA.load_key(key_file) pk = EVP.PKey() pk.assign_rsa(rsa_key) x = X509.Request() x.set_pubkey(pk) name = x.get_subject() name.C = "US" name.ST = "Michigan" name.L = "Ann Arbor" name.O = "EFF" name.OU = "University of Michigan" name.CN = domains[0] extstack = X509.X509_Extension_Stack() ext = X509.new_extension('subjectAltName', ", ".join(["DNS:%s" % d for d in domains])) extstack.push(ext) x.add_extensions(extstack) x.sign(pk,'sha256') assert x.verify(pk) pk2 = x.get_pubkey() assert x.verify(pk2) return x.as_pem(), x.as_der()
def create_certificate_signing_request(subjectPrivKey, subjectInfo, version = 0, hash = 'sha1'): """ Create a certificate signing request (CSR) and return CSR in PEM and text formats. :param subjectPrivKey: Subject private RSA key in PEM format. :type subjectPrivKey: str :param subjectInfo: Subject information. :type subjectInfo: dict :param version: CSR version. :type version: int :param hash: CSR signing hash, one of 'sha1', 'sha256', .. :type hash: str :returns tuple -- (CSR in PEM format, CSR as text). """ skey = RSA.load_key_bio(BIO.MemoryBuffer(subjectPrivKey)) if skey.check_key() != 1: raise Exception("invalid subject RSA key") p_skey = EVP.PKey(md = hash) p_skey.assign_rsa(skey) csr = X509.Request() csr.set_version(version) csr.set_pubkey(p_skey) subject = x509name_from_info(subjectInfo) csr.set_subject(subject) csr.sign(p_skey, hash) return (csr.as_pem(), csr.as_text())
def makeRequest(pk): """ Creates a new CSR from an RSA key :param pk: RSA key :return: CSR """ pkey = EVP.PKey() pkey.assign_rsa(pk) req = X509.Request() req.set_version(2) req.set_pubkey(pkey) name = X509.X509_Name() name.CN = 'cirosec gmbh' req.set_subject_name(name) ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com') ext2 = X509.new_extension('nsComment', 'Hello there') extstack = X509.X509_Extension_Stack() extstack.push(ext1) extstack.push(ext2) assert (extstack[1].get_name() == 'nsComment') req.add_extensions(extstack) req.sign(pkey, 'sha1') return req
def mkreq(self, bits, ca=0): pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, self.callback) pk.assign_rsa(rsa) rsa = None # should not be freed here x.set_pubkey(pk) name = x.get_subject() name.C = "UK" name.CN = "OpenSSL Group" if not ca: ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com') ext2 = X509.new_extension('nsComment', 'Hello there') extstack = X509.X509_Extension_Stack() extstack.push(ext1) extstack.push(ext2) x.add_extensions(extstack) with self.assertRaises(ValueError): x.sign(pk, 'sha513') x.sign(pk, 'sha1') self.assertTrue(x.verify(pk)) pk2 = x.get_pubkey() self.assertTrue(x.verify(pk2)) return x, pk
def CrearPedidoCertificado(self, cuit="", empresa="", nombre="pyafipws", filename="empresa.csr"): "Crear un certificate signing request (X509 CSR)" from M2Crypto import RSA, EVP, X509 # create the certificate signing request (CSR): self.x509_req = X509.Request () # normalizar encoding (reemplazar acentos, eñe, etc.) if isinstance(empresa, unicode): empresa = unicodedata.normalize('NFKD', empresa).encode('ASCII', 'ignore') if isinstance(nombre, unicode): nombre = unicodedata.normalize('NFKD', nombre).encode('ASCII', 'ignore') # subjet: C=AR/O=[empresa]/CN=[nombre]/serialNumber=CUIT [nro_cuit] x509name = X509.X509_Name () # default OpenSSL parameters: kwargs = {"type": 0x1000 | 1, "len": -1, "loc": -1, "set": 0} x509name.add_entry_by_txt(field='C', entry='AR', **kwargs) x509name.add_entry_by_txt(field='O', entry=empresa, **kwargs) x509name.add_entry_by_txt(field='CN', entry=nombre, **kwargs) x509name.add_entry_by_txt(field='serialNumber', entry="CUIT %s" % cuit, **kwargs) self.x509_req.set_subject_name(x509name) # sign the request with the previously created key (CrearClavePrivada) self.x509_req.set_pubkey (pkey=self.pkey) self.x509_req.sign(pkey=self.pkey, md='sha256') # save the CSR result to a file: f = open(filename, "w") f.write(self.x509_req.as_pem()) f.close()
def genSignature(privkey, sig_domain="WangYang", sig_depart="", sig_organization="IIE", sig_province="Beijing", sig_locale="Beijing"): #首先载入密钥文件。此文件同时保存了申请者的私钥与公钥。 pkey=EVP.load_key_string(privkey, util.no_passphrase_callback) req=X509.Request() req.set_pubkey(pkey) #包含公钥 #req.set_version(1) #身份信息不是简单的字符串。而是X509_Name对象。 name=X509.X509_Name() #CN是Common Name的意思。如果是一个网站的电子证书,就要写成网站的域名 name.CN = sig_domain # "WangYang" # 普通名字 #Organization Unit,通常是指部门吧,组织内单元 name.OU = sig_depart # "SKLOIS" #Organization。通常是指公司 name.O = sig_organization # "IIE" #State or Province。州或者省 name.ST = sig_province # "Beijing" #Locale。 name.L = sig_locale # "Beijing" #国家。不能直接写国家名字,比如China之类的,而应该是国家代码。 #CN代表中国。US代表美国,JP代表日本 name.C="CN" # 国家名称 req.set_subject(name) #包含通信节点的身份信息 req.sign(pkey, "sha256") #使用通信节点的密钥进行签名,sha1已经不安全了,这里使用sha256 signature = req.as_pem() return signature
def generate_certificate_request(self, cr, uid, ids, x509_name, context=None): """ Generate new certificate request for pairkey. """ if context is None: context = {} r = {} for signer in self.browse(cr, uid, ids): # Create certificate structure pk = EVP.PKey() req = X509.Request() pem_string = signer.key.encode('ascii') + '\n' + signer.pub.encode( 'ascii') rsa = RSA.load_key_string(pem_string) pk.assign_rsa(rsa) req.set_pubkey(pk) req.set_subject(x509_name) # Crete certificate object certificate_obj = self.pool.get('crypto.certificate') w = { 'name': x509_name.as_text(), 'csr': req.as_pem(), 'pairkey_id': signer.id, } r[signer.id] = certificate_obj.create(cr, uid, w) return r
def mk_request(bits, CN, C, ST, L, O, OU): """Create a X509 request with the given number of bits in they key. :param bits: number of RSA key bits :param CN: Common Name field :param C: Country Name :param ST: State or province name :param L: Locality :param O: Organization :param OU: Organization Unit :returns: a X509 request and the private key (EVP) """ pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, lambda: None) pk.assign_rsa(rsa) x.set_pubkey(pk) subject_name = X509.X509_Name() subject_name.add_entry_by_txt(field="CN", type=ASN1.MBSTRING_ASC, entry=CN or "", len=-1, loc=-1, set=0) subject_name.add_entry_by_txt(field="C", type=ASN1.MBSTRING_ASC, entry=C or "", len=-1, loc=-1, set=0) subject_name.add_entry_by_txt(field="ST", type=ASN1.MBSTRING_ASC, entry=ST or "", len=-1, loc=-1, set=0) subject_name.add_entry_by_txt(field="L", type=ASN1.MBSTRING_ASC, entry=L or "", len=-1, loc=-1, set=0) subject_name.add_entry_by_txt(field="O", type=ASN1.MBSTRING_ASC, entry=O or "", len=-1, loc=-1, set=0) subject_name.add_entry_by_txt(field="OU", type=ASN1.MBSTRING_ASC, entry=OU or "", len=-1, loc=-1, set=0) x.set_subject_name(subject_name) x.sign(pk, 'sha256') return x, pk
def make_proxy_request(bits, subject): pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, lambda: None) pk.assign_rsa(rsa) x.set_pubkey(pk) x.set_subject(subject) x.sign(pk, 'sha1') return x, pk
def req(name): rsa = RSA.load_key(name + '_key.pem') pk = EVP.PKey() pk.assign_rsa(rsa) reqqed = X509.Request() reqqed.set_pubkey(pk) reqqed.set_subject(make_subject()) reqqed.sign(pk, 'sha1') return reqqed, pk
def create_request(self, **subject): request = X509.Request() subject_name = X509.X509_Name() for key, value in subject.iteritems(): setattr(subject_name, key, value) request.set_subject(subject_name) request.set_pubkey(pkey=self.pkey) request.sign(self.pkey, md="sha256") return request
def _genCsr(self): rsa = RSA.gen_key(self._key_size, 65537) rsapem = rsa.as_pem(cipher=None) evp = EVP.PKey() evp.assign_rsa(rsa) rsa = None # should not be freed here csr = X509.Request() csr.set_pubkey(evp) csr.sign(evp, 'sha1') return rsapem, csr.as_pem(), csr.get_pubkey().as_pem(cipher=None)
def GetCSR(self): """Return our CSR in pem format.""" csr = X509.Request() pk = EVP.PKey() rsa = self._LoadOurCertificate() pk.assign_rsa(rsa) csr.set_pubkey(pk) name = csr.get_subject() name.CN = str(self.common_name) csr.sign(pk, "sha1") return csr.as_pem()
def req(name): rsa = RSA.load_key(name + '_key.pem') pk = EVP.PKey() pk.assign_rsa(rsa) req = X509.Request() req.set_pubkey(pk) n = req.get_subject() n.C = 'US' n.O = 'M2Crypto ' + name n.CN = 'localhost' req.sign(pk, 'sha256') return req, pk
def _genCsr(self): rsa = RSA.gen_key(self._key_size, 65537) rsapem = rsa.as_pem(cipher=None) evp = EVP.PKey() evp.assign_rsa(rsa) pub_bio = BIO.MemoryBuffer() rsa.save_pub_key_bio(pub_bio) pubkeypem = pub_bio.getvalue() rsa = None # should not be freed here csr = X509.Request() csr.set_pubkey(evp) csr.sign(evp, 'sha1') return rsapem, csr.as_pem(), pubkeypem
def _genReq(self): rsa = RSA.gen_key( self.environment[owspcons.ConfigEnv.KEY_SIZE], 65537, ) rsapem = rsa.as_pem(cipher=None) evp = EVP.PKey() evp.assign_rsa(rsa) rsa = None # should not be freed here req = X509.Request() req.set_pubkey(evp) req.sign(evp, 'sha1') return rsapem, req.as_pem()
def gen_csr(pkey): """Create an x509 CSR (Certificate Signing Request) Equivalent to: openssl req -new -key client.key -out client.csr :param pkey: key :type pkey: EVP.PKey :return: x509 request :rtype: X509.Request """ csr = X509.Request() csr.set_pubkey(pkey) return csr
def mk_request(bits, cn='localhost'): pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, lambda: None) pk.assign_rsa(rsa) x.set_pubkey(pk) name = x.get_subject() name.C = "CN" name.CN = cn name.ST = 'TS' name.O = 'TS' name.OU = 'TS' x.sign(pk, 'sha1') return x, pk
def generateProxyRequest(dnList): # By convention, use the longer representation userDN = dnList[-1] requestKeyPair = RSA.gen_key(512, 65537, callback=_muteCallback) requestPKey = EVP.PKey() requestPKey.assign_rsa(requestKeyPair) request = X509.Request() request.set_pubkey(requestPKey) request.set_subject(populatedName([('O', 'Dummy')])) request.set_version(0) request.sign(requestPKey, 'md5') return (request, requestPKey)
def _make_cert_request(cn, rsa, uid=None): pub_key = EVP.PKey() request = X509.Request() pub_key.assign_rsa(rsa) request.set_pubkey(pub_key) subject = request.get_subject() subject.nid['UID'] = 458 # openssl lacks support for userid subject.CN = "%s" % cn if uid: subject.UID = uid ext2 = X509.new_extension('nsComment', 'Pulp Identity Certificate for Consumer: [%s]' % cn) extensions = X509.X509_Extension_Stack() extensions.push(ext2) request.add_extensions(extensions) request.sign(pub_key, 'sha256') return request, pub_key
def make_x509_request(uuid, csrpath, keypath): rsa = generateRSAKey() pkey = makePKey(rsa) req = X509.Request() req.set_pubkey(pkey) name = X509.X509_Name() name.CN = uuid req.set_subject_name(name) req.sign(pkey, 'sha1') req.save(csrpath) rsa.save_key(keypath, cipher=None) message = {} message['uuid'] = name.CN with open(csrpath, 'r') as fd: message['csr'] = fd.read() return message
def create(self): """Create certificate request; return certificate request file.""" try: pkey = self._gen_and_save_key(self.key_file) except IOError: msg = 'Failed to open key file: ' + self.key_file raise error.NotFound(msg) name = self._gen_x509_name(self.cn) req = X509.Request() req.set_version(3) req.set_pubkey(pkey) req.set_subject_name(name) req.sign(pkey, 'sha1') req.save(self.req_file) result = self.get() return result
def create_self_signed_RootCA_certificate(root_ca_info, sign_method="sha256", days=3650): # Setp 1: Create RSA-key pair (public/private key) rsa = generate_rsa_keypair(2048, 65537) private_key = EVP.PKey() private_key.assign_rsa(rsa) # Step 2-1: Prepare X.509 Certificate Signed Request req = X509.Request() req.set_pubkey(private_key) x509_name = req.get_subject() x509_name.C = root_ca_info["C"] x509_name.CN = root_ca_info["CN"] x509_name.ST = root_ca_info["ST"] x509_name.L = root_ca_info["L"] x509_name.O = root_ca_info["O"] x509_name.OU = root_ca_info["OU"] req.sign(private_key, sign_method) # Step 2-2: Prepare X.509 certificate root_ca_cert = X509.X509() serial = struct.unpack("<Q", os.urandom(8))[0] root_ca_cert.set_serial_number(serial) root_ca_cert.set_version(3) # Setp 2-3: Set required information of RootCA certificate root_ca_cert.set_issuer(x509_name) root_ca_cert.set_subject(root_ca_cert.get_issuer()) root_ca_cert.set_pubkey(req.get_pubkey()) # Get the CSR's public key # Step 2-4: Set Valid Date for RootCA certificate t = int(time.time()) now = ASN1.ASN1_UTCTIME() now.set_time(t) expire = ASN1.ASN1_UTCTIME() expire.set_time(t + days * 24 * 60 * 60) root_ca_cert.set_not_before(now) root_ca_cert.set_not_after(expire) # Step 3: Add Extensions for this Root CA certificate root_ca_cert.add_ext(X509.new_extension('basicConstraints', 'CA:TRUE')) root_ca_cert.add_ext( X509.new_extension('subjectKeyIdentifier', root_ca_cert.get_fingerprint())) # Step 4: Use Root CA's RSA private key to sign this certificate root_ca_cert.sign(private_key, sign_method) return root_ca_cert, private_key
def _generate_proxy_request(): """ Generates a X509 proxy request. Returns: A tuple (X509 request, generated private key) """ key_pair = RSA.gen_key(1024, 65537, callback=_mute_callback) pkey = EVP.PKey() pkey.assign_rsa(key_pair) x509_request = X509.Request() x509_request.set_pubkey(pkey) x509_request.set_subject(_populated_x509_name([('O', 'Dummy')])) x509_request.set_version(0) x509_request.sign(pkey, 'sha256') return x509_request, pkey
def _make_cert_request(uid, rsa): pub_key = EVP.PKey() x = X509.Request() pub_key.assign_rsa(rsa) rsa = None # should not be freed here x.set_pubkey(pub_key) name = x.get_subject() name.CN = "%s" % uid ext2 = X509.new_extension( 'nsComment', 'Pulp Generated Identity Certificate for Consumer: [%s]' % uid) extstack = X509.X509_Extension_Stack() extstack.push(ext2) x.add_extensions(extstack) x.sign(pub_key, 'sha1') pk2 = x.get_pubkey() return x, pub_key
def gen_req(): """ Generate TLS certificate request for testing """ logging.info('Generating test certificate request') key = EVP.PKey() req = X509.Request() rsa = RSA.gen_key(1024, 65537, callback) key.assign_rsa(rsa) req.set_pubkey(key) name = req.get_subject() name.C = 'US' name.CN = 'minifi-listen' req.sign(key, 'sha256') return req, key
def make_request(pkey, cn): req = X509.Request() req.set_version(2) req.set_pubkey(pkey) name = X509.X509_Name() name.CN = cn req.set_subject_name(name) ext1 = X509.new_extension('subjectAltName', 'DNS:foobar.example.com') ext2 = X509.new_extension('nsComment', 'Hello there') extstack = X509.X509_Extension_Stack() extstack.push(ext1) extstack.push(ext2) assert (extstack[1].get_name() == 'nsComment') req.add_extensions(extstack) return req
def __init__(self, private_key, digest=None, **kwargs): evp = private_key._new_evp() req = X509.Request() req.set_pubkey(evp) subj = X509.X509_Name() for key, value in kwargs.iteritems(): setattr(subj, key, value) req.set_subject(subj) req.sign(evp, digest or DEFAULT_REQ_SIGN_DIGEST) assert req.verify(evp) == 1 self._req = req
def generate_certificate_request(self, x509_name): """ Generate new certificate request for pairkey. """ # Create certificate structure pk = EVP.PKey() req = X509.Request() pem_string = self.key.encode('ascii') + '\n' + self.pub.encode('ascii') rsa = RSA.load_key_string(pem_string) pk.assign_rsa(rsa) req.set_pubkey(pk) req.set_subject(x509_name) w = { 'name': x509_name.as_text(), 'csr': req.as_pem(), 'pairkey_id': self.id, } return self.env['crypto.certificate'].create(w)