Introduction
OCSP stapling is a TLS extension in which the server fetches a fresh signed OCSP response from the CA's OCSP responder and presents it to the client during the TLS handshake, so the client does not need to make a separate OCSP call. OCSP itself was defined by the IETF in RFC 2560 in 1999 and updated by RFC 6960 in 2013; the stapling mechanism was added to TLS by RFC 6066 in 2011. A Java learner should care because OCSP stapling is the standard real-time revocation mechanism used by every modern browser and by Spring Boot's TLS implementation, and understanding it is essential for building fast, secure TLS services that do not require clients to make secondary network calls.
This tutorial walks through an OCSP stapling java program that uses the sun.security.provider.certpath.OCSP class to query an OCSP responder, then demonstrates how the server would attach the OCSP response to the TLS handshake via the JDK's SSLParameters.setStatusResponseExtension. The program focuses on the OCSP request and response mechanics; the integration with the TLS handshake is shown conceptually.
What is OCSP Stapling?
OCSP is the Online Certificate Status Protocol: the client sends a request containing the certificate's serial number to the CA's OCSP responder, and the responder returns a signed response saying "good", "revoked", or "unknown". The response is short (typically a few hundred bytes), signed by the CA's OCSP signing key, and valid for a few hours.
The problem with plain OCSP is that the client must make a separate network call to the OCSP responder during the TLS handshake. This adds latency, leaks which site the user is visiting to the CA (because the CA sees the OCSP request), and breaks if the OCSP responder is offline or blocked by a firewall. The browsers Chrome and Firefox work around these issues with their own private OCSP caches, but the privacy leak remains.
OCSP stapling solves these problems by having the server fetch the OCSP response from the CA on a schedule (typically every few hours) and present the cached response during the TLS handshake. The client verifies the response signature using the CA's public key, checks the validity window, and uses the certificate based on the response status. No client-side OCSP fetch is needed; no privacy leak; no extra latency.
OCSP stapling differs from CRL checking in that OCSP gives a real-time, per-certificate response, while CRLs give a batch, periodic list. OCSP stapling pushes the response from CA to server to client, while plain OCSP requires the client to fetch the response. Stapling is the standard for modern TLS; CRLs are used as a fallback or in enterprise environments with strict offline requirements.
How OCSP Stapling Works - Step by Step
Step 1: Discover the OCSP responder URL. The certificate's Authority Information Access (AIA) extension (OID 1.3.6.1.5.5.7.1.1) contains an OCSP access method with a URL. Parse the extension to extract the URL.
Step 2: Build the OCSP request. The request contains one or more CertID structures, each identifying a certificate by its issuer name hash, issuer key hash, and serial number. The request can be unsigned (most common) or signed.
Step 3: POST the request to the OCSP responder. The OCSP HTTP protocol uses POST with the DER-encoded request as the body and content-type application/ocsp-request.
Step 4: Parse the OCSP response. The response contains a response status (successful, malformed, internal error, try later, signature required, unauthorized), an optional response bytes containing the BasicOCSPResponse with the signer certificate, the producedAt time, the nextUpdate time, and a list of responses each containing a CertID, the cert status (good, revoked, unknown), thisUpdate, and nextUpdate.
Step 5: Verify the response signature. The response is signed by either the CA itself or a delegated OCSP signing certificate (the OCSP signer must have the ExtendedKeyUsage extension with the OCSP signing OID). Verify the signature using the signer's public key.
Step 6: Check freshness. The producedAt and nextUpdate times define the validity window. The current time must be within this window; otherwise the response is stale.
Step 7: Check the certificate status. Look up the certificate's CertID in the response and read the cert status. If good, the certificate is valid; if revoked, reject the connection; if unknown, fall back to CRL or refuse the connection.
Step 8: Staple to the TLS handshake. The server caches the OCSP response bytes and sends them to the client in the TLS status_request extension. The client performs Steps 4 through 7 with the cached response.
Java Program for OCSP Stapling
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;
import sun.security.provider.certpath.OCSP;
import sun.security.provider.certpath.OCSP.RevocationStatus;
import sun.security.provider.certpath.OCSP.RevocationStatus.CertStatus;
import sun.security.x509.X500Name;
import sun.security.x509.CertificateValidity;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSubjectName;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.CertificateVersion;
import sun.security.x509.AlgorithmId;
public class OcspStaplingDemo {
public static void main(String[] args) throws Exception {
// 1. Generate a CA keypair and a leaf certificate.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair caKp = kpg.generateKeyPair();
KeyPair leafKp = kpg.generateKeyPair();
X509Certificate caCert = selfSigned(caKp, "CN=imcseian-ca, C=US", 10);
X509Certificate leafCert = signedBy(caKp.getPrivate(), leafKp.getPublic(),
"CN=localhost, O=imcseian, C=US", "CN=imcseian-ca, C=US", 1);
// 2. Print the AIA extension (OCSP responder URL).
byte[] aia = leafCert.getExtensionValue("1.3.6.1.5.5.7.1.1");
System.out.println("AIA extension present: " + (aia != null));
if (aia == null) {
System.out.println("Note: real production certificates carry an AIA with the");
System.out.println("OCSP responder URL. For this demo we will construct the");
System.out.println("OCSP request manually and use a real responder URL.");
}
// 3. Build the OCSP request manually (DER encoded) for the leaf certificate.
byte[] ocspRequest = buildOcspRequest(caCert, leafCert.getSerialNumber());
System.out.println("OCSP request size: " + ocspRequest.length + " bytes");
// 4. In production, POST the request to the OCSP responder URL.
// For this demo we print the request structure rather than make a network call.
System.out.println("OCSP request (hex, first 16 bytes): "
+ toHex(ocspRequest, 16));
// 5. Parse a fake OCSP response demonstrating the structure.
// Real OCSP responses are returned by the responder as DER-encoded BasicOCSPResponse.
System.out.println("\nIn production:");
System.out.println(" - Server fetches OCSP response every 4 hours");
System.out.println(" - Server caches the response bytes");
System.out.println(" - During TLS handshake, server sends the cached response");
System.out.println(" - Client verifies the response signature and freshness");
System.out.println(" - If status is GOOD, certificate is accepted");
// 6. Demonstrate the OCSP verification API on a locally built response.
RevocationStatus status = queryLocal(caCert, leafCert);
System.out.println("\nLocal OCSP check result:");
System.out.println(" Status: " + status.getCertStatus());
System.out.println(" Revocation time: " + status.getRevocationTime());
}
static byte[] buildOcspRequest(X509Certificate issuer, BigInteger serial) throws Exception {
// Build the CertID: hash of issuer name, hash of issuer key, serial.
byte[] issuerNameHash = java.security.MessageDigest.getInstance("SHA-1")
.digest(issuer.getSubjectX500Principal().getEncoded());
byte[] issuerKeyHash = java.security.MessageDigest.getInstance("SHA-1")
.digest(issuer.getPublicKey().getEncoded());
// Manually assemble a minimal OCSPRequest DER (simplified):
// SEQUENCE { requestName TBSRequest }
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
baos.write(0x30); // SEQUENCE tag
baos.write(0x05); // length 5
baos.write(0x30); // inner SEQUENCE
baos.write(0x03); // length 3
baos.write(0x02); // INTEGER tag
baos.write(0x01); // length 1
baos.write(0x00); // version 0
// Real OCSP requests are larger; this is a structural demo.
return baos.toByteArray();
}
static RevocationStatus queryLocal(X509Certificate issuer, X509Certificate cert) {
// Returns a placeholder status. Real code would call
// sun.security.provider.certpath.OCSP.check(cert, issuer, ...).
return new RevocationStatus() {
@Override public CertStatus getCertStatus() { return CertStatus.GOOD; }
@Override public java.util.Date getRevocationTime() { return null; }
};
}
static String toHex(byte[] bytes, int limit) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(limit, bytes.length); i++) {
sb.append(String.format("%02x", bytes[i] & 0xff));
}
return sb.toString();
}
static X509Certificate selfSigned(KeyPair kp, String subject, int years) throws Exception {
return signedBy(kp.getPrivate(), kp.getPublic(), subject, subject, years);
}
static X509Certificate signedBy(java.security.PrivateKey signerKey,
java.security.PublicKey subjectPub,
String subjectDn, String issuerDn,
int years) throws Exception {
X500Name subject = new X500Name(subjectDn);
X500Name issuer = new X500Name(issuerDn);
Date notBefore = new Date(System.currentTimeMillis() - 60_000);
Date notAfter = new Date(System.currentTimeMillis() + years * 365L * 24 * 60 * 60 * 1000);
CertificateValidity validity = new CertificateValidity(notBefore, notAfter);
X509CertInfo info = new X509CertInfo();
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
info.set(X509CertInfo.SERIAL_NUMBER,
new CertificateSerialNumber(new BigInteger(64, new SecureRandom())));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(subject));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuer));
info.set(X509CertInfo.VALIDITY, validity);
info.set(X509CertInfo.KEY, new CertificateX509Key(subjectPub));
info.set(X509CertInfo.ALGORITHM_ID,
new CertificateAlgorithmId(AlgorithmId.get("SHA256withRSA")));
X509CertImpl impl = new X509CertImpl(info);
impl.sign(signerKey, "SHA256withRSA");
return impl;
}
}
Code Explanation - Line by Line
The main method starts by generating a CA keypair and a leaf certificate signed by the CA. In a real OCSP deployment the CA's certificate would be a real public CA root, and the leaf certificate would be issued by that CA. The CA's OCSP responder would be running at a URL published in the certificate's Authority Information Access (AIA) extension.
The AIA extension check demonstrates how to look up the extension by OID. The AIA extension has OID 1.3.6.1.5.5.7.1.1, and its value is a sequence of access descriptions, each containing an access method (OCSP for the OCSP responder URL, CAIssuers for the CA's certificate URL) and the access location (typically a URI encoded as a GeneralName). In production you would parse this extension to extract the OCSP responder URL.
The buildOcspRequest method constructs a minimal OCSP request in DER format. A real OCSP request is an ASN.1 structure containing a CertID (issuer name hash, issuer key hash, serial number) for each certificate to be checked, plus optional extensions. The CertID is built by hashing the issuer's name DER and the issuer's public key bytes with SHA-1, and including the certificate's serial number. The full DER encoding is more complex than our simplified 5-byte demo; the Bouncy Castle library has a complete OCSPReqBuilder class that produces valid requests.
The queryLocal method returns a placeholder status demonstrating the RevocationStatus API. In production, you would call sun.security.provider.certpath.OCSP.check(cert, issuer, ...) which performs the full HTTP fetch, response parsing, and signature verification. The result is a RevocationStatus with getCertStatus() returning GOOD, REVOKED, or UNKNOWN.
The toHex helper formats bytes in lowercase hex for the diagnostic print. The first 16 bytes of the OCSP request show the DER structure starting with 0x30 (the SEQUENCE tag), which is how the responder identifies the request format.
In production, the server would call buildOcspRequest, POST it to the responder URL using HttpURLConnection with content-type application/ocsp-request, parse the response bytes with CertificateFactory.getInstance("X.509").generateCRL or a dedicated OCSP response parser, verify the signature, cache the response until nextUpdate, and then send the cached response bytes to every client during the TLS handshake using SSLParameters.setStatusResponseExtension("status_request", StaplingRequestSupport.enable()).
Sample Input and Output
AIA extension present: false Note: real production certificates carry an AIA with the OCSP responder URL. For this demo we will construct the OCSP request manually and use a real responder URL. OCSP request size: 7 bytes OCSP request (hex, first 16 bytes): 30053003020100 In production: - Server fetches OCSP response every 4 hours - Server caches the response bytes - During TLS handshake, server sends the cached response - Client verifies the response signature and freshness - If status is GOOD, certificate is accepted Local OCSP check result: Status: GOOD Revocation time: null
The output confirms that the local stub returns GOOD status, that the OCSP request DER starts with the expected 0x30 SEQUENCE tag, and that the production workflow is summarized for clarity. Real OCSP responses would be hundreds of bytes long and signed by the CA.
Common Mistakes to Avoid
The most common mistake is disabling OCSP checking in production because it adds latency. The right fix is OCSP stapling, not disabling the check. Disabling OCSP checking means your client accepts revoked certificates, which is a security violation.
The second mistake is failing to verify the OCSP response signature. An attacker who controls the network could substitute a forged response saying "good" for a revoked certificate. Always verify the response signature using the CA's public key or the delegated OCSP signing certificate (which itself must chain back to the CA and have the OCSP signing ExtendedKeyUsage).
The third mistake is failing to check the response freshness. The response is valid only between thisUpdate and nextUpdate. A response past nextUpdate is stale and should be rejected. Most responders set nextUpdate to a few hours after thisUpdate; the server should refresh the cache before nextUpdate expires.
The fourth mistake is failing to staple the response on the server side. If your server does not staple, every client has to do its own OCSP fetch, which leaks privacy and adds latency. Configure your TLS server to fetch and staple OCSP responses; in nginx this is ssl_stapling on, in Apache it is SSLOpenSSLStapling on, in Spring Boot you need to enable it programmatically via the underlying Tomcat or Netty configuration.
Real-World Applications
OCSP stapling is the standard revocation mechanism for modern browsers. Chrome, Firefox, Safari, and Edge all prefer OCSP stapling over plain OCSP or CRL checking. The Chrome CRLSets mechanism is a parallel system that uses pushed updates from Google for emergency revocations (such as the DigiNotar breach in 2011), but the day-to-day revocation check in modern TLS is OCSP stapling.
Let's Encrypt and most other public CAs publish OCSP responders that support stapling. The nginx directive ssl_stapling on; and the Apache directive SSLOpenSSLStapling on; enable server-side stapling. Spring Boot requires either Tomcat's SSLStaplingEnabled configuration or a custom SSLContext with status response enabled.
Java's HttpClient in JDK 11+ supports OCSP stapling via the SSLContext configuration. The standard X509TrustManagerImpl checks the stapled response if present during the TLS handshake, falling back to a separate OCSP fetch if the stapled response is missing or stale. The system property com.sun.net.ssl.checkRevocation enables revocation checking for the legacy SSLSocket API.
In the broader ecosystem, OpenSSL performs OCSP stapling via the SSL_set_tlsext_status_type and SSL_CTX_set_tlsext_status_arg functions. BoringSSL and NSS (Mozilla's TLS library) have equivalent APIs. The Bouncy Castle library has a complete OCSP client in the org.bouncycastle.cert.ocsp package that does not require sun.security internals.
If you are building a CA, an OCSP responder, or a TLS server in Java, the OCSP API and SSLParameters.setStatusResponseExtension are the standard entry points. For higher-level workflows, the Bouncy Castle OCSPReqBuilder and BasicOCSPResp classes produce and parse the wire format with full RFC compliance.
Conclusion
OCSP stapling is the standard real-time revocation mechanism for TLS, letting the server present a cached signed OCSP response during the handshake so the client does not need a separate network call. We built a Java program that constructs an OCSP request, demonstrates the request structure, and shows the production workflow. Next, study the mTLS post to see how client certificates fit into the same TLS handshake, and the TLS 1.3 Handshake post to see how stapling integrates into the modern handshake.
Comments
Comments
Post a Comment