Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract CN from X509Certificate in Java?

I am using a SslServerSocket and client certificates and want to extract the CN from the SubjectDN from the client's X509Certificate.

At the moment I call cert.getSubjectX500Principal().getName() but this of course gives me the total formatted DN of the client. For some reason I am just interested in the CN=theclient part of the DN. Is there a way to extract this part of the DN without parsing the String myself?

like image 961
Martin C. Avatar asked May 26 '10 15:05

Martin C.


People also ask

What is X509Certificate in Java?

public abstract class X509Certificate extends Certificate. Abstract class for X. 509 v1 certificates. This provides a standard way to access all the version 1 attributes of an X. 509 certificate.

What is the difference between X509Certificate and x509Certificate2?

It can be used to get information about an existing certificate (valid dates, issuer, etc.). It had simple methods/operations (i.e. reading a cert from disk). The x509Certificate2 is a subclass of x509Certificate with additional functionality. It represents an actual X509 certificate.

What is javax servlet X509Certificate?

servlet. request. X509Certificate"); This checks if the service that needs mutual SSL gets a certificate that is valid. So when that URL gets called, the servlet filter checks for cert.


2 Answers

Here's some code for the new non-deprecated BouncyCastle API. You'll need both bcmail and bcprov distributions.

X509Certificate cert = ...;  X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0];  return IETFUtils.valueToString(cn.getFirst().getValue()); 
like image 115
gtrak Avatar answered Sep 18 '22 18:09

gtrak


here is another way. the idea is that the DN you obtain is in rfc2253 format, which is the same as used for LDAP DN. So why not reuse the LDAP API?

import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn;  String dn = x509cert.getSubjectX500Principal().getName(); LdapName ldapDN = new LdapName(dn); for(Rdn rdn: ldapDN.getRdns()) {     System.out.println(rdn.getType() + " -> " + rdn.getValue()); } 
like image 30
Jakub Avatar answered Sep 19 '22 18:09

Jakub