The Common Name (CN) is a critical field within an X509 certificate that identifies the entity owning the certificate. In Java, you can extract the CN from an X509 certificate using several approaches. This article will explore multiple approaches.
1. Understanding the Common Name (CN) in X509 Certificates
The Common Name (CN) is a key attribute within an X.509 certificate’s Subject Distinguished Name (DN). It typically represents the entity to which the certificate is issued, such as a server or an individual. In the context of SSL/TLS certificates, the CN is often the fully qualified domain name (FQDN) of the server the certificate is protecting.
1.1 Structure of X.509 Certificate
An X.509 certificate contains various pieces of information, including:
- Version: The version of the X.509 standard.
- Serial Number: A unique identifier for the certificate.
- Signature Algorithm: The algorithm used to sign the certificate.
- Issuer: The entity that issued the certificate.
- Validity Period: The start and end dates when the certificate is valid.
- Subject: The entity the certificate is issued to, containing the CN.
- Public Key: The public key of the subject.
- Extensions: Additional attributes and information.
1.2 Example of a Distinguished Name (DN)
Here’s an example of a DN containing a CN:
CN=www.example.com, O=Example Organization, L=San Francisco, ST=California, C=US
In this DN:
- CN:
www.example.com
(Common Name) - O:
Example Organization
(Organization) - L:
San Francisco
(Locality) - ST:
California
(State or Province) - C:
US
(Country)
1.3 Importance of CN
The CN is crucial in SSL/TLS certificates as it is often used by clients (like web browsers) to verify that the certificate matches the domain they are connecting to. The client will typically display a security warning if the CN does not match the domain name.
1.4 Prerequisites
- Java Development Kit (JDK): Ensure you have JDK installed. Java 8 or later is recommended.
- An X.509 Certificate
2. Using Regular Expressions
Using regular expressions to extract the CN from an X.509 certificate involves parsing the Subject Distinguished Name (DN) string of the certificate. This method leverages Java’s built-in regex capabilities to identify and extract the CN.
public class RegularExpressionsCNExtractor { // Loading the Certificate public static X509Certificate loadCertificate(String filePath) throws Exception { try (FileInputStream fis = new FileInputStream(filePath)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(fis); } } // Extracting CN with Regular Expressions public static String extractCN(X509Certificate certificate) throws Exception { String subjectDN = certificate.getSubjectX500Principal().getName(); String cn = null; Pattern pattern = Pattern.compile("CN=([^,]+)"); Matcher matcher = pattern.matcher(subjectDN); if (matcher.find()) { cn = matcher.group(1); } else { throw new Exception("CN not found in Subject DN"); } return cn; } public static void main(String[] args) throws Exception { X509Certificate certificate = loadCertificate("src/main/resources/javacodegeeks.com.cer"); String cn = extractCN(certificate); System.out.println("Common Name: " + cn); } }
In this example, the loadCertificate
method loads an X.509 certificate from a specified file path. The extractCN
method uses a regular expression to parse the Subject DN and extract the CN. The main method loads a certificate and extracts its CN, printing the result to the console.
3. Using Bouncy Castle
Bouncy Castle is a powerful library for handling cryptographic operations in Java. It provides tools for manipulating X.509 certificates, making it easier to extract the CN from the certificate’s subject.
3.1 Adding Bouncy Castle Dependency
Add the following dependency to your pom.xml
if you’re using Maven:
<dependencies> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk18on</artifactId> <version>1.76</version> </dependency> </dependencies>
3.2 Loading and Extracting CN
The Bouncy Castle library simplifies the extraction of the CN by providing a structured way to handle X.509 certificates.
public class BouncyCastleCNExtractor { public static X509Certificate loadCertificate(String filePath) throws Exception { try (FileInputStream fis = new FileInputStream(filePath)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(fis); } } public static String extractCN(X509Certificate certificate) throws Exception { X500Name x500Name = new JcaX509CertificateHolder(certificate).getSubject(); return x500Name.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString(); } public static void main(String[] args) { try { X509Certificate certificate = loadCertificate("src/main/resources/ca.cer"); String cn = extractCN(certificate); System.out.println("CN: " + cn); } catch (Exception e) { } } }
In this example, The BouncyCastleCNExtractor
class first loads the certificate and uses Bouncy Castle’s X500Name
class to parse the subject and extract the CN.
4. Using Cryptacular Library
Cryptacular is another library that provides utilities for cryptographic operations in Java. It includes functionality to handle X.509 certificates and extract attributes like the CN.
4.1 Adding Cryptacular Dependency
Add the following dependency to your pom.xml
:
<dependencies> <dependency> <groupId>org.cryptacular</groupId> <artifactId>cryptacular</artifactId> <version>1.2.6</version> </dependency> </dependencies>
4.2 Extract CN
The CryptacularCNExtractor
class below demonstrates how to load the certificate and extract the CN.
public class CryptacularCNExtractor { public static X509Certificate loadCertificate(String filePath) throws Exception { try (FileInputStream fis = new FileInputStream(filePath)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(fis); } } public static String extractCN(X509Certificate certificate) throws Exception { String subjectName = CertUtil.subjectCN(certificate); return subjectName; } public static void main(String[] args) { try { X509Certificate certificate = loadCertificate("src/main/resources/ca.cer"); String cn = extractCN(certificate); System.out.println("CN: " + cn); } catch (Exception e) { } } }
Cryptacular simplifies the extraction of the CN by providing the CertUtil
class with methods for common operations on X.509 certificates. The method CertUtil.subjectCN(certificate)
is used to extract the Common Name (CN) from the subject of the X.509 certificate.
5. Using LDAP API
The Java Naming and Directory Interface (JNDI) API, which is included in the JDK, can be used to parse distinguished names (DNs) and extract attributes like the Common Name (CN) from an X.509 certificate. Here’s how you can use the standard LDAP API from the JDK to accomplish this task.
5.1 Example Code
public class LDAPApiCNExtractor { // Method to load an X.509 certificate from a file public static X509Certificate loadCertificate(String filePath) throws Exception { try (FileInputStream fis = new FileInputStream(filePath)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); return (X509Certificate) cf.generateCertificate(fis); } } // Method to extract the CN from the certificate's subject DN public static String extractCN(X509Certificate certificate) throws Exception { // Get the subject DN from the certificate String subjectDN = certificate.getSubjectX500Principal().getName(); // Parse the DN using JNDI's LdapName class LdapName ldapName = new LdapName(subjectDN); // Iterate through the RDNs to find the CN for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { return rdn.getValue().toString(); } } // If no CN is found, throw an exception throw new Exception("CN not found in Subject DN"); } public static void main(String[] args) { try { // Load the certificate from a file X509Certificate certificate = loadCertificate("src/main/resources/javacodegeeks.com.cer"); // Extract and print the CN String cn = extractCN(certificate); System.out.println("CN: " + cn); } catch (Exception e) { } } }
In this example, we use the loadCertificate
method to read the certificate from a specified file path using a FileInputStream
while the CertificateFactory
is used to generate an X509Certificate
from the input stream.
Extracting the CN: The extractCN
method retrieves the subject DN of the certificate using certificate.getSubjectX500Principal().getName()
. The DN is parsed using LdapName, which breaks the DN string into its Relative Distinguished Names (RDNs). The method then iterates through the list of RDNs to find the one with the type CN (Common Name). If a CN is found, its value is returned as a string. If no CN is found, an exception is thrown.
Output is:
6. Conclusion
Extracting the CN from an X.509 certificate in Java can be done in multiple ways, depending on your preferences and the libraries you have available. This guide provided examples using regular expressions, Bouncy Castle, Cryptacular, and the LDAP API, each offering different levels of complexity and features.
7. Download
This was an article on how to extract a common name from a x509 certificate in Java.
You can download the full source code of this example here: Java extract common name x509 certificate