Skip to content
IRC-CodingIRC-Coding
PKIPublic Key InfrastructureCertificatesCertificate AuthorityTLS SSLX.509Root CAOCSPCRL

PKI Public Key Infrastructure: Certificates & TLS/SSL

PKI framework for digital certificates. Root CA, Intermediate CA, X.509, CRL, OCSP and TLS/SSL implementation with examples.

S

schutzgeist

5 min read
PKI Public Key Infrastructure: Certificates & TLS/SSL

PKI Public Key Infrastructure: Certificates, CAs & TLS/SSL

This guide provides a comprehensive overview of Public Key Infrastructure – covering certificates, Certificate Authorities, and TLS/SSL implementation.

In a Nutshell

PKI is the organizational and technical framework for creating, distributing, validating, and revoking public keys through certificates. It enables trusted identities for people, machines, and services.

Technical Definition

A Public Key Infrastructure (PKI) consists of a Root CA and subordinate Intermediate CAs that issue, sign, and revoke X.509 certificates using CRL or OCSP.

Core Components:

  • Certificate Authority (CA): Issues certificates
  • Registration Authority (RA): Verifies identities
  • Certificate Repository: Stores certificates
  • Validation Authority: Validates certificates

Certificate Contents:

  • Public Key: The certificate holder’s public key
  • Identity Information: CN, SAN, OU, O, C
  • Validity Period: Certificate expiration timeframe
  • Key Usage: Intended purpose of the key
  • Digital Signature: Signature from the issuing CA

Trust Model:

  • Chain of Trust: Hierarchical CA structure
  • Root Certificates: Trust anchors in truststores
  • Certificate Validation: Verification of the certificate chain

PKI supports authentication, digital signatures, encryption, and non-repudiation in TLS, S/MIME, code signing, and mTLS.

Exam-Relevant Topics

  • Root CA and Intermediate CA hierarchy
  • X.509 certificate format and contents
  • Chain of Trust and Truststore management
  • CRL (Certificate Revocation List) and OCSP (Online Certificate Status Protocol)
  • TLS/SSL handshake with certificate validation
  • CSR (Certificate Signing Request) process
  • mTLS (Mutual TLS) for client authentication
  • IHK-relevant for IT security and network technology

Core Components

  1. Root Certificate Authority: The top trust authority
  2. Intermediate Certificate Authority: Intermediate instances for delegation
  3. End Entity Certificate: Certificate for servers, clients, or services
  4. Certificate Signing Request: Request for certificate issuance
  5. Certificate Revocation List: List of revoked certificates
  6. OCSP Responder: Online certificate status checking
  7. Truststore: Storage for trusted root certificates
  8. Keystore: Storage for own certificates and private keys

Practical Examples

Creating a Certificate with OpenSSL

# Generate private key
openssl genrsa -out server.key 2048

# Create Certificate Signing Request (CSR)
openssl req -new -key server.key -out server.csr \
  -subj "/C=DE/ST=Berlin/L=Berlin/O=IRC-Coding/OU=IT/CN=irc-coding.de"

# Self-signed certificate (for testing)
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

# Display certificate
openssl x509 -in server.crt -text -noout

# Verify certificate
openssl verify -CAfile ca.crt server.crt

Java Keystore Management

// Create keystore with keytool
// keytool -genkeypair -alias server -keyalg RSA -keysize 2048 \
//   -keystore keystore.jks -validity 365

// Export CSR
// keytool -certreq -alias server -keystore keystore.jks -file server.csr

// Import certificate
// keytool -importcert -alias server -file server.crt \
//   -keystore keystore.jks -trustcacerts

// Java code for certificate validation
import java.security.cert.*;
import java.io.FileInputStream;

public class CertificateValidator {
    
    public static boolean validateCertificate(String certPath, String caPath) {
        try {
            // Load certificate
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) 
                cf.generateCertificate(new FileInputStream(certPath));
            
            // Load CA certificate
            X509Certificate caCert = (X509Certificate) 
                cf.generateCertificate(new FileInputStream(caPath));
            
            // Validate certificate chain
            cert.checkValidity(); // Check validity period
            cert.verify(caCert.getPublicKey()); // Verify signature
            
            // CRL/OCSP check (simplified)
            if (isRevoked(cert)) {
                return false;
            }
            
            return true;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    private static boolean isRevoked(X509Certificate cert) {
        // Implement CRL or OCSP check
        return false;
    }
}

TLS Server with Node.js

const https = require('https');
const fs = require('fs');

// TLS server configuration
const tlsOptions = {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.crt'),
    ca: fs.readFileSync('ca.crt'), // For client authentication
    requestCert: true,            // Require mTLS
    rejectUnauthorized: true       // Reject invalid certificates
};

const server = https.createServer(tlsOptions, (req, res) => {
    // Client certificate information
    const clientCert = req.socket.getPeerCertificate();
    
    if (clientCert) {
        console.log('Client authenticated:', clientCert.subject.CN);
        res.writeHead(200);
        res.end('Hello authenticated client!');
    } else {
        res.writeHead(401);
        res.end('Client certificate required');
    }
});

server.listen(8443, () => {
    console.log('TLS Server listening on port 8443');
});

Python TLS Client with Certificate Validation

import ssl
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.ssl_ import create_urllib3_context

class TLSAdapter(HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        context = create_urllib3_context()
        context.check_hostname = True
        context.verify_mode = ssl.CERT_REQUIRED
        context.load_verify_locations('ca.crt')  # Load CA certificate
        
        # mTLS with client certificate
        context.load_cert_chain('client.crt', 'client.key')
        
        kwargs['ssl_context'] = context
        return super().init_poolmanager(*args, **kwargs)

# TLS client with certificate validation
session = requests.Session()
session.mount('https://', TLSAdapter())

try:
    response = session.get('https://secure-api.example.com/data')
    print("Response:", response.json())
except requests.exceptions.SSLError as e:
    print("TLS Error:", e)
except Exception as e:
    print("General Error:", e)

Certificate Revocation (CRL/OCSP)

// CRL-based revocation check
import java.security.cert.*;
import java.net.URL;
import java.io.InputStream;

public class CRLValidator {
    
    public static boolean checkRevocation(X509Certificate cert) {
        try {
            // Extract CRL distribution points from certificate
            String crlUrl = getCRLDistributionPoint(cert);
            
            if (crlUrl != null) {
                // Download CRL
                URL url = new URL(crlUrl);
                InputStream in = url.openStream();
                
                // Load and validate CRL
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509CRL crl = (X509CRL) cf.generateCRL(in);
                
                // Check if certificate is revoked
                return !crl.isRevoked(cert);
            }
            
            return true; // No CRL available
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    private static String getCRLDistributionPoint(X509Certificate cert) {
        // Extract CRL distribution point from certificate extensions
        // Implementation would require ASN.1 parsing
        return null;
    }
}

PKI Hierarchy and Trust Chain

Typical PKI Structure

Root CA (self-signed)
├── Intermediate CA 1 (for web servers)
│   ├── irc-coding.de
│   └── api.irc-coding.de
├── Intermediate CA 2 (for code signing)
│   ├── desktop-app.exe
│   └── mobile-app.apk
└── Intermediate CA 3 (for email)
    ├── user1@irc-coding.de
    └── user2@irc-coding.de

Certificate Validation Chain

public class ChainValidator {
    
    public static boolean validateChain(X509Certificate[] chain, 
                                       X509Certificate[] trustedCAs) {
        try {
            // Initialize trust anchors
            Set<TrustAnchor> trustAnchors = new HashSet<>();
            for (X509Certificate ca : trustedCAs) {
                trustAnchors.add(new TrustAnchor(ca, null));
            }
            
            // Configure PKIX parameters
            PKIXParameters params = new PKIXParameters(trustAnchors);
            params.setRevocationEnabled(true); // Enable CRL/OCSP checking
            
            // Certificate path builder
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(chain[0]);
            
            PKIXBuilderParameters builderParams = 
                new PKIXBuilderParameters(trustAnchors);
            builderParams.setRevocationEnabled(true);
            
            // Validate certificate chain
            CertPathBuilderResult result = builder.build(builderParams);
            CertPathValidator validator = CertPathValidator.getInstance("PKIX");
            CertPathValidatorResult validatorResult = 
                validator.validate(result.getCertPath(), params);
            
            return true;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

Advantages and Disadvantages

Advantages of PKI

  • Security: Strong cryptographic foundation
  • Scalability: Hierarchical structure for large organizations
  • Standardization: X.509 is widely adopted
  • Flexibility: Supports various use cases (TLS, code signing, etc.)
  • Non-repudiation: Digital signatures prove authorship

Disadvantages

  • Complexity: Requires elaborate setup and maintenance
  • Cost: Commercial CAs charge fees
  • Operational overhead: Key rotation, certificate management
  • Single point of failure: Root CA outage affects the entire PKI

Common Exam Questions

  1. What’s the difference between Root CA and Intermediate CA? Root CA is self-signed and serves as the trust anchor, while Intermediate CA is signed by Root CA and delegates certificate issuance.

  2. Explain the Chain of Trust! Hierarchical validation flows from the end-entity certificate through Intermediate CAs up to the Root CA.

  3. What’s the purpose of CRL and OCSP? They verify whether certificates have been revoked before expiration (due to compromise, job changes, etc.).

  4. When do you use mTLS? For mutual authentication between server and client (APIs, microservices).

Key References

  1. https://de.wikipedia.org/wiki/Public-Key-Infrastruktur
  2. https://tools.ietf.org/html/rfc5280
  3. https://www.ietf.org/rfc/rfc5280.txt
Back to Blog
Share:

Related Posts