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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With