PKI & Certificate Management
๐ฅ Vibe Prompt
"Set up a local CA with openssl. Issue a server cert and a client cert. Verify mTLS connection."
# Step 1: Root CA
openssl genrsa -out root-ca.key 4096
openssl req -x509 -new -nodes -key root-ca.key \
-days 3650 -out root-ca.crt \
-subj "/C=TW/O=VibeTutor/CN=VibeTutor Root CA"
# Step 2: Server cert
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr \
-subj "/C=TW/O=VibeTutor/CN=api.vibetutor.com"
openssl x509 -req -in server.csr -CA root-ca.crt \
-CAkey root-ca.key -CAcreateserial \
-days 365 -out server.crt
# Step 3: Verify
openssl verify -CAfile root-ca.crt server.crt
mTLS (Mutual TLS)
# Client cert
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr \
-subj "/C=TW/O=VibeTutor/CN=client-1"
openssl x509 -req -in client.csr -CA root-ca.crt \
-CAkey root-ca.key -days 365 -out client.crt
# Verify chain
openssl verify -CAfile root-ca.crt server.crt client.crt
Certificate Chain
Root CA (self-signed, offline)
โโโ Intermediate CA (operational)
โโโ Server Cert (api.example.com)
โโโ Server Cert (app.example.com)
โโโ Client Certs (microservices)
Chapter Summary
- Understand core concepts and principles
- Master implementation methods and techniques
- Familiar with common issues and solutions
- Able to apply in real projects
Further Reading
- Official documentation and API references
- Open source examples on GitHub
- Technical books and online courses
- Community discussions and tech blogs
Implementation Example
Basic Example
# This section provides a complete implementation example
Steps
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- Optimization: Improve performance
Common Errors
| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |
Code Example
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
References
- Official documentation
- API reference
- Open source examples
- Community discussions
X.509 Certificate Structure
An X.509 digital certificate binds a public key to an identity.
Certificate Fields
| Field | Description | Example | |-------|-------------|---------| | Version | X.509 version (1, 2, 3) | 3 | | Serial Number | Unique identifier | 0x1234ABCD | | Signature Algorithm | Algorithm used to sign | sha256WithRSAEncryption | | Issuer | CA that issued the cert | C=US, O=Let's Encrypt | | Validity | Not before / Not after | 2024-01-01 to 2025-01-01 | | Subject | Entity the cert belongs to | CN=example.com | | Public Key | Public key and algorithm | RSA 2048 bits | | Extensions | Additional features | SAN, Key Usage, etc. |
Certificate Chain
Root CA (self-signed)
โโโ Intermediate CA
โโโ Leaf Certificate (your website)
Creating Certificates with OpenSSL
Self-Signed Certificate (Development)
# Generate private key
openssl genrsa -out server.key 2048
# Create CSR
openssl req -new -key server.key -out server.csr \
-subj "/C=TW/ST=Taipei/L=Taipei/O=MyOrg/CN=localhost"
# Self-sign the certificate
openssl x509 -req -days 365 -in server.csr \
-signkey server.key -out server.crt
# View certificate details
openssl x509 -in server.crt -text -noout
CA-Signed Certificate (Production)
# Step 1: Generate private key and CSR
openssl req -new -newkey rsa:2048 -nodes \
-keyout example.com.key \
-out example.com.csr \
-subj "/CN=example.com"
# Step 2: Send CSR to CA (Let's Encrypt, DigiCert, etc.)
# Step 3: CA returns signed certificate
# Step 4: Configure web server
# Nginx example:
# ssl_certificate /etc/ssl/example.com.crt;
# ssl_certificate_key /etc/ssl/example.com.key;
Let's Encrypt (Free SSL)
# Install certbot
brew install certbot # macOS
apt install certbot # Ubuntu
# Obtain certificate
certbot certonly --standalone -d example.com -d www.example.com
# Certificate location
# /etc/letsencrypt/live/example.com/fullchain.pem
# /etc/letsencrypt/live/example.com/privkey.pem
# Auto-renew (cron job)
# certbot renew --quiet
Certificate Validation in Python
import ssl
import socket
from datetime import datetime
def check_certificate(hostname: str, port: int = 443):
"""Check SSL certificate details for a host."""
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
subject = dict(x[0] for x in cert['subject'])
issuer = dict(x[0] for x in cert['issuer'])
not_before = datetime.strptime(
cert['notBefore'], '%b %d %H:%M:%S %Y %Z'
)
not_after = datetime.strptime(
cert['notAfter'], '%b %d %H:%M:%S %Y %Z'
)
return {
"subject": subject.get('commonName', ''),
"issuer": issuer.get('organizationName', ''),
"valid_from": not_before.isoformat(),
"valid_until": not_after.isoformat(),
"expires_in_days": (not_after - datetime.now()).days,
"sans": cert.get('subjectAltName', []),
"serial": cert.get('serialNumber', '')
}
# Check example.com
info = check_certificate("example.com")
for key, value in info.items():
print(f"{key}: {value}")
Certificate Pinning
Certificate pinning associates a host with its expected certificate or public key.
| Method | What You Pin | Flexibility | |--------|-------------|-------------| | Certificate pinning | Full certificate (SPKI) | Low โ must update on renewal | | Public key pinning | Public key hash | Medium โ key can stay across renewals | | CA pinning | Root or intermediate CA | High โ any cert from trusted CA |
# Example: Public key pinning (HPKP-style)
import hashlib
def get_pin(cert_path: str):
"""Generate a public key pin for a certificate."""
with open(cert_path, 'rb') as f:
cert_data = f.read()
from cryptography import x509
from cryptography.hazmat.primitives import hashes
cert = x509.load_pem_x509_certificate(cert_data)
public_key = cert.public_key()
public_key_bytes = public_key.public_bytes_raw()
pin = hashlib.sha256(public_key_bytes).digest()
return base64.b64encode(pin).decode()
Summary
PKI provides the trust infrastructure for secure internet communication. Certificates bind identities to public keys, and certificate chains establish trust through CAs.
Key takeaways:
- X.509 certificate binds a public key to an identity (domain, person, device) |
- Certificate chain: Root CA โ Intermediate CA โ Leaf cert |
- Use Let's Encrypt for free, automated SSL certificates |
- Self-signed certs are for development only |
- OpenSSL creates and inspects certificates via CLI |
- Validate certificates programmatically with Python ssl module |
- Certificate pinning adds extra security against CA compromise |
- Always monitor certificate expiry to prevent outages |
What's Next: TLS 1.3
The next chapter covers TLS 1.3 protocol โ how HTTPS secures web traffic.