views:

452

answers:

2

Hi,

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?

Best regards, Martin

+1  A: 

You could try getName(X500Principal.RFC2253, oidMap) or getName(X500Principal.CANONICAL, oidMap) to see which formats the DN string better. Maybe one of the oidMap map values will be the string you want.

Gilbert Le Blanc
+4  A: 

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);
laz