如何在Java中从X509Certificate中提取CN? [英] How to extract CN from X509Certificate in Java?

查看:22
本文介绍了如何在Java中从X509Certificate中提取CN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SslServerSocket 和客户端证书,并希望从客户端的 X509Certificate 的 SubjectDN 中提取 CN.

I am using a SslServerSocket and client certificates and want to extract the CN from the SubjectDN from the client's X509Certificate.

目前我调用 cert.getSubjectX500Principal().getName() 但这当然给了我客户端的总格式化 DN.出于某种原因,我只对 DN 的 CN=theclient 部分感兴趣.有没有办法在不自己解析字符串的情况下提取DN的这部分?

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?

推荐答案

这是新的未弃用 BouncyCastle API 的一些代码.您将需要 bcmail 和 bcprov 分发版.

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

这篇关于如何在Java中从X509Certificate中提取CN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆