Last active
April 25, 2020 17:43
-
-
Save angelbarrera92/3af37a328db04c4eb4e116b0f40d1709 to your computer and use it in GitHub Desktop.
Generate Kubernetes client certificates using own CA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
from OpenSSL import crypto | |
import base64 | |
########### | |
# CA Cert # | |
########### | |
with open("ca.key", "r") as my_cert_file: | |
my_cert_text = my_cert_file.read() | |
ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM, my_cert_text) | |
with open("ca.crt", "r") as my_cert_file: | |
my_cert_text = my_cert_file.read() | |
ca_crt = crypto.load_certificate(crypto.FILETYPE_PEM, my_cert_text) | |
ca_subj = ca_crt.get_subject() | |
############### | |
# Client Cert # | |
############### | |
client_key = crypto.PKey() | |
client_key.generate_key(crypto.TYPE_RSA, 4096) | |
client_cert = crypto.X509() | |
client_cert.set_version(2) | |
client_cert.set_serial_number(random.randint(50000000,100000000)) | |
client_subj = client_cert.get_subject() | |
client_subj.commonName = "kubernetes-admin" | |
client_subj.organizationName = "system:masters" | |
client_cert.add_extensions([ | |
crypto.X509Extension(b"keyUsage", True, b"digitalSignature"), | |
crypto.X509Extension(b"extendedKeyUsage", False, b"clientAuth,serverAuth"), | |
crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=client_cert), | |
]) | |
client_cert.set_issuer(ca_subj) | |
client_cert.set_pubkey(client_key) | |
client_cert.gmtime_adj_notBefore(0) | |
client_cert.gmtime_adj_notAfter(1*365*24*60*60) | |
client_cert.sign(ca_key, 'sha256') | |
client_crt_b64_bytes = base64.b64encode(crypto.dump_certificate(crypto.FILETYPE_PEM, client_cert)) | |
client_key_b64_bytes = base64.b64encode(crypto.dump_privatekey(crypto.FILETYPE_PEM, client_key)) | |
print(client_crt_b64_bytes.decode("utf-8")) | |
print() | |
print(client_key_b64_bytes.decode("utf-8")) | |
# # Save certificate | |
with open("client.crt", "wb") as f: | |
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, client_cert)) | |
# # Save private key | |
with open("client.key", "wb") as f: | |
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, client_key)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pyOpenSSL==19.1.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment