3

I want to retrieve a string from the certificate subject field but only its CN value.

to get the whole string I use:

Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String aliass = (String) enumeration.nextElement();
    X509Certificate cer = (X509Certificate) ks.getCertificate(aliass);
    String s = cer.getSubjectDN().getName().;
    System.out.println(s);
}

output is: CN=something, OU=something, DC=something, DC=something, DC=someting

as stated I want to retrieve only the CN string. is there a short way about it or I should play with substring methods to get the field, also that would not be my preferred way because some certs.getName() are starting with their email address.

oliholz
  • 7,447
  • 2
  • 43
  • 82
caniaskyouaquestion
  • 657
  • 2
  • 11
  • 21

2 Answers2

4

I think that there is no explicit method to get the common name from the certificate using java API (you can get the whole subjectDN an parse it to get the CN), if you want a method to do so use BouncyCastle classes instead:

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.style.IETFUtils;

Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String aliass = (String) enumeration.nextElement();
    X509Certificate cer = (X509Certificate) ks.getCertificate(aliass);
    X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
    String s = IETFUtils.valueToString(cn.getFirst().getValue());
    System.out.println(s);
}

Hope this helps,

albciff
  • 18,112
  • 4
  • 64
  • 89
  • thanks..will try your code, i have parsed it already. but thanks,def more slicker way of doing it is your way. – caniaskyouaquestion Oct 06 '14 at 14:01
  • You're welcome, I saw that you have some other questions related to the digital-signature and PKI, probably you've already an answer for them however I'll try to answer a few `:)`. – albciff Oct 06 '14 at 19:23
  • yes, I managed to answer almost all of them, but the PKCS11 slot issue is still there, I turned away from it and did it WINDOWS-MY way...but would like to do it the other way also @albciff. Thanks a lot – caniaskyouaquestion Oct 07 '14 at 10:32
0

According to the javadoc you can try the following:

cer.getSubjectX500Principal()
WeMakeSoftware
  • 9,039
  • 5
  • 34
  • 52