从证书DN中解析CN [英] Parsing the CN out of a certificate DN

查看:514
本文介绍了从证书DN中解析CN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我说这是一个美学问题。我已经解决了我自己的问题,我只是对更好的方法感到好奇。

Let me begin by stating that this is a question of aesthetics. I've solved my own problem, I'm just curious about better ways of doing it.

所以,我有一个证书DN,像这样:

So, I've got a certificate DN, something like this:

CN = Jimmy Blooptoop,OU = Someplace,OU =员工,DC = Bloopsoft-Inc

CN=Jimmy Blooptoop,OU=Someplace,OU=Employees,DC=Bloopsoft-Inc

现在,我想要从中获取CN。在java中,除了使用Xoun9证书中的完整DN而没有使用像bouncy castle这样的第三方库时,没有原生支持可以抓取任何东西 - 我无法使用它。所以我必须解析它,这不是什么大问题。唯一让它有点棘手的事实是,CN并不总是被格式化为< first name> <姓氏> 。通常情况下,它实际上将是<姓氏>,<名字> < middle initial> 。因此,在上面的例子中,CN可以是Jimmy Blooptoop或Blooptoop,Jimmy J(当然是Joop的缩写)。

Now, I want to grab the CN out of that. In java, there isn't native support to grab anything but the full DN from the X509 certificate without using some 3rd party library like bouncy castle - which I can't use. So I've got to parse it out, which isn't much of problem. The only thing that makes it slightly tricky is the fact that the CN isn't always going to be formatted as <first name> <last name>. More often than not, it's actually going to be <last name>, <first name> <middle initial>. So, in the example above, the CN could be Jimmy Blooptoop or Blooptoop, Jimmy J (short for the Joop of course).

在阅读了有关常规的内容之后表达式,我写了以下内容,效果很好:

After going and reading up about about regular expressions, I wrote the following, which works well enough:

Matcher m = Pattern.compile("CN=[A-Za-z]*[, ]*[ A-Za-z]*").matcher(dn);
if (m.find())
  cn = m.group();

我只是好奇,如果表达式看起来不像废话。我非常有信心,因为我在阅读了正则表达式的介绍之后就已经解决了这个问题。

I'm just curious if there are expressions that would look less like crap. I'm fairly confident that there are since I worked that out after reading just an introduction to regex.

推荐答案

怎么样 javax.naming.ldap.LdapName

String dn = "CN=Jimmy Blooptoop,OU=Someplace,OU=Employees,DC=Bloopsoft-Inc";
LdapName ln = new LdapName(dn);

for(Rdn rdn : ln.getRdns()) {
    if(rdn.getType().equalsIgnoreCase("CN")) {
        System.err.println("CN is: " + rdn.getValue());
        break;
    }
}

由于缺少某些东西,它不是最漂亮的界面比如 LdapName#getByType(String)但它可以省去你必须考虑DN可能有什么奇怪功能的麻烦。

It's not the most beautiful interface since there is something missing like LdapName#getByType(String) but it saves you the trouble of having to think about what strange features DNs might have.

这篇关于从证书DN中解析CN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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