Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Get Client Certificate from HttpServletRequest

In HTTP SSL authentication, client send its valid Certificate to server to check authenticity. Server validates the request and allow access to resources if authentication is successful.

In this post, I am going to show you, how to read the ssl certitificate information that comes as value of request header filed 'ssl_client_cert'.

Step 1: Read the certificate information.
String certificateInfo = request.getHeader(ssl_client_cert);

Step 2: Create input stream to the certificateInfo.
InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(certificateInfo)

Step 3: Convert the stream to X509 certificate.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(is);

CertUtil.java
package com.sample.util;

import java.io.InputStream;
import java.security.cert.CertificateFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.util.Base64;
import java.security.cert.X509Certificate;

/**
*
* Utility class to read the certificate information from the request header
* 'ssl_client_cert'.
*
* If request is Null (or) do not have header value 'ssl_client_cert' it returns
* null, else return X509Certificate. In exceptional cases it returns null.
*
* @author Krishna
*
*/
public class CertUtil {
private static final String SSL_CLIENT_CERT_HEADER = "ssl_client_cert";

/**
*
* @param request
* @return
*/
public X509Certificate getCertificate(HttpServletRequest request) {
if (request == null) {
return null;
}

/* Read the certificate information from the header 'ssl_client_cert' */
String certificateInfo = request.getHeader(SSL_CLIENT_CERT_HEADER);

if (certificateInfo == null || certificateInfo.isEmpty()) {
return null;
}

try (InputStream is = new ByteArrayInputStream(Base64.getDecoder().decode(certificateInfo))) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
return cert;
} catch (Exception e) {
return null;
}
}
}

You may like
Interview Questions
Miscellaneous
Reading pkcs12 certificate information
Java cacerts file
Load Client Certificates from Windows Operating system
Load Client Certificates from MAC Operating system
Export public key certificate from keystore
Convert byte array to private, public keys
Digital Signature




This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

How to Get Client Certificate from HttpServletRequest

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×