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?
Advertisement
Answer
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());