def cmd_mkcert(workingdir, name): cwd = os.getcwd() try: fs_util.ch_dir(workingdir) priv = read_private() cacert = load_cert_by_path('cacert.crt') ca_pk = serialization.load_pem_private_key(priv[0]['ca'], password=None, backend=default_backend()) cert, pk = ca_impl.mk_signed_cert(cacert, ca_pk, name, priv[0]['lastserial'] + 1) with open('%s-cert.crt' % name, 'wb') as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) priv[0][name] = pk.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) # increment serial number after successful creation priv[0]['lastserial'] += 1 write_private(priv) with os.fdopen( os.open("%s-private.pem" % name, os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as f: f.write(priv[0][name]) with os.fdopen( os.open("%s-public.pem" % name, os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as f: f.write(pk.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo)) cc = load_cert_by_path('%s-cert.crt' % name) pubkey = cacert.public_key() pubkey.verify( cc.signature, cc.tbs_certificate_bytes, padding.PKCS1v15(), cc.signature_hash_algorithm, ) logger.info( f"Created certificate for name {name} successfully in {workingdir}" ) except crypto_exceptions.InvalidSignature: logger.error("ERROR: Cert does not validate against CA") finally: os.chdir(cwd)
def test_cfssl(self): _ = ca_impl_cfssl.mk_cacert("my ca") (ca_cert, ca_pk, _) = ca_impl_cfssl.mk_cacert() cert, _ = ca_impl_cfssl.mk_signed_cert(ca_cert, ca_pk, "cert", _) pubkey = ca_cert.public_key() try: pubkey.verify( cert.signature, cert.tbs_certificate_bytes, padding.PKCS1v15(), cert.signature_hash_algorithm, ) except crypto_exceptions.InvalidSignature: self.fail("Certificate signature validation failed.")
def cmd_mkcert(workingdir, name): cwd = os.getcwd() try: config.ch_dir(workingdir, logger) priv = read_private() cacert = X509.load_cert('cacert.crt') ca_pk = EVP.load_key_string(priv[0]['ca']) cert, pk = ca_impl.mk_signed_cert(cacert, ca_pk, name, priv[0]['lastserial'] + 1) with open('%s-cert.crt' % name, 'wb') as f: f.write(cert.as_pem()) f = BIO.MemoryBuffer() pk.save_key_bio(f, None) priv[0][name] = f.getvalue() f.close() # increment serial number after successful creation priv[0]['lastserial'] += 1 write_private(priv) # write out the private key with password with os.fdopen( os.open("%s-private.pem" % name, os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as f: biofile = BIO.File(f) pk.save_key_bio(biofile, None) biofile.close() pk.get_rsa().save_pub_key('%s-public.pem' % name) cc = X509.load_cert('%s-cert.crt' % name) if cc.verify(cacert.get_pubkey()): logger.info( f"Created certificate for name {name} successfully in {workingdir}" ) else: logger.error("ERROR: Cert does not validate against CA") finally: os.chdir(cwd)