Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving subject/CN field from a certificate?

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.

like image 816
caniaskyouaquestion Avatar asked Oct 23 '25 19:10

caniaskyouaquestion


1 Answers

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,

like image 67
albciff Avatar answered Oct 26 '25 09:10

albciff