How to extract CN from X509Certificate in Java?
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());
As an alternative to gtrak's code that does not need ''bcmail'':
X509Certificate cert = ...;
X500Principal principal = cert.getSubjectX500Principal();
X500Name x500name = new X500Name( principal.getName() );
RDN cn = x500name.getRDNs(BCStyle.CN)[0]);
return IETFUtils.valueToString(cn.getFirst().getValue());
@Jakub: I have used your solution until my SW had to be run on Android. And Android does not implement javax.naming.ldap :-(
If adding dependencies isn't a problem you can do this with Bouncy Castle's API for working with X.509 certificates:
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PrincipalUtil;
import org.bouncycastle.jce.X509Principal;
...
final X509Principal principal = PrincipalUtil.getSubjectX509Principal(cert);
final Vector<?> values = principal.getValues(X509Name.CN);
final String cn = (String) values.get(0);
Update
At the time of this posting, this was the way to do this. As gtrak mentions in the comments however, this approach is now deprecated. See gtrak's updated code that uses the new Bouncy Castle API.
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());
}