Skip to content
IRC-Coding IRC-Coding
PKI Public Key Infrastructure Certificates Certificate Authority TLS SSL

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 practical examples.

S

schutzgeist

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

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

This article is a comprehensive explanation of Public Key Infrastructure – including 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.

Compact Technical Description

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

Main components:

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

Certificate contents:

  • Public Key: Subject’s public key
  • Identity Information: CN, SAN, OU, O, C
  • Validity Period: Certificate validity timeframe
  • Key Usage: Key purpose binding
  • Digital Signature: Signature of issuing CA

Trust model:

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

PKI supports authentication, signature, encryption, and non-repudiation in TLS, S/MIME, Code Signing, and mTLS.

Exam-Relevant Key Points

  • 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: Top trust instance
  2. Intermediate Certificate Authority: Intermediate instances for delegation
  3. End Entity Certificate: Certificate for servers/clients/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 of trusted root certificates
  8. Keystore: Storage of 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

# Validate 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()); // Check 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 was 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 used
  • Flexibility: Various use cases (TLS, Code Signing, etc.)
  • Non-repudiation: Digital signatures prove authorship

Disadvantages

  • Complexity: Elaborate setup and maintenance
  • Costs: Commercial CAs charge fees
  • Operational burden: Key rotation, certificate management
  • Single point of failure: Root CA failure affects entire PKI

Common Exam Questions

  1. What is the difference between Root CA and Intermediate CA? Root CA is self-signed and a trust anchor, Intermediate CA is signed by Root CA and delegates issuance.

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

  3. What is the purpose of CRL and OCSP? Checking whether certificates were revoked before expiration (compromise, job change, etc.).

  4. When is mTLS used? For mutual authentication between server and client (APIs, microservices).

Most Important Sources

  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: