Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
make a certificate signing request that you can use with mkcert
#!/usr/bin/env python3
from OpenSSL import crypto, SSL
from typing import List, Optional
import sys
import os
import errno
def get_or_make_key(cn: str) -> crypto.PKey:
key_filename = cn + "-key.pem"
if os.path.exists(key_filename):
with open(key_filename, "r") as f:
key = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
print("Loaded private key from", key_filename)
return key
else:
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
with open(key_filename, "wb") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
print("Wrote new private key to", key_filename)
return key
def make_csr(names: List[str]):
if len(names) < 1:
usage()
cn = names[0]
csr_filename = cn + ".csr"
if os.path.exists(csr_filename):
print("CSR file", csr_filename, "exists, exiting.")
sys.exit(errno.EEXIST)
key = get_or_make_key(cn)
req = crypto.X509Req()
req.get_subject().countryName = b"US"
req.get_subject().commonName = cn.encode("ascii")
req.set_pubkey(key)
req.add_extensions(
[
crypto.X509Extension(
b"keyUsage",
True,
b"Digital Signature, Non Repudiation, Key Encipherment",
),
crypto.X509Extension(b"basicConstraints", True, b"CA:FALSE"),
crypto.X509Extension(
b"subjectAltName",
True,
b",".join([("DNS:" + n).encode("ascii") for n in names]),
),
]
)
req.sign(key, "sha1")
with open(csr_filename, "wb") as f:
f.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, req))
print("Wrote new private key to", csr_filename)
def usage():
print("Usage: `mkcsr cn [san1 san2 ...]`")
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) < 2:
usage()
make_csr(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.