Writing a Custom Certificate Authority (CA) with cryptography

Introduction

A Certificate Authority (CA) is a trusted entity that issues digital certificates. With Python’s cryptography library, you can create your own CA for internal networks, test environments, or development purposes.


Table of Contents

  • Introduction

  • What is a Certificate Authority?

  • Installing cryptography

  • Creating a CA Certificate

  • Sample Code

  • Use Cases

  • Conclusion


What is a Certificate Authority?

A CA validates identity and issues certificates used in TLS/SSL. These certificates enable encrypted communication between clients and servers.


Installing cryptography

bash
pip install cryptography

Creating a CA Certificate

Sample Code:

python
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptography.x509.oid import NameOID
import datetime

# Generate CA private key
ca_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

# Certificate subject and issuer
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My CA"),
x509.NameAttribute(NameOID.COMMON_NAME, u"myca.example.com"),
])

# Build certificate
ca_cert = x509.CertificateBuilder().subject_name(subject).issuer_name(issuer)\
.public_key(ca_key.public_key()).serial_number(x509.random_serial_number())\
.not_valid_before(datetime.datetime.utcnow())\
.not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=3650))\
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)\
.sign(ca_key, hashes.SHA256())

# Save to files
with open("ca_cert.pem", "wb") as f:
f.write(ca_cert.public_bytes(serialization.Encoding.PEM))

with open("ca_key.pem", "wb") as f:
f.write(ca_key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()
))


Use Cases

  • Testing TLS in development environments

  • Creating certificates for internal services

  • Generating signed certificates


Conclusion

Creating a custom CA with Python is useful for testing secure communications or managing certificates in internal environments. The cryptography library makes this process accessible and powerful.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top