如何从Java中的X509Certificate中提取CN

如何从Java中的X509Certificate中提取CN

本文介绍了如何从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的这一部分而不自己解析String?

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 06:00