How to parse security certificate subcomponents?

雨燕双飞 提交于 2019-12-23 02:59:07

问题


I'm reading the subject from a security certificate, which has the following format...

CN=x,OU=y,O=z,ST=v,C=COM

I want to parse this String and get the CN only. Is there any easy way to do this?


回答1:


Is it possible to use simple regular expressions here?

Without tried it and out of my mind:

Pattern pattern  = Pattern.compile("CN=([^\\,])\\,")
Matcher matcher = pattern.matcher(text);
if ( matcher.find() )
{
  for (int index=1; index<matcher.groupCount();index++)
  {
    String cnValue = matcher.group(index);
  }
}



回答2:


Working version of Omnaest's answer:

Pattern pattern  = Pattern.compile("CN=([^\\,]*)");
Matcher matcher = pattern.matcher(text);
String cnValue = matcher.find() ? matcher.group(1) : null;



回答3:


You can use CompoundName of jndi

Name dn = parser.parse("CN=x,OU=y,O=z,ST=v,C=COM");
dn.get(dn.size());

For an example have a look at this link

Edit: Added a working example

public static void main(String args[]){

    try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:389");
        Context ctx = new InitialContext(env);
        NameParser parser = ctx.getNameParser("");
        Name dn = parser.parse("CN=x,OU=y,O=z,ST=v,C=COM");

        System.out.println(dn.size() + dn.get( dn.size() -1  ));
    }catch(NamingException e) {
        e.printStackTrace();
    }
}

To create the context you have to connect to a ldap server however. Its easy to do a string parsing and get the first rdn. But do not get there! The DN have different formats. In DCE format the dn will be separated as CN=x/OU=y/O=z/ST=v/C=COM

EDIT: Added another example without connecting to ldap server

import javax.naming.ldap.LdapName;
....

public static void main(String args[]){

  try {
      LdapName dn = new LdapName("CN=x,OU=y,O=z,ST=v,C=COM");
      System.out.println(dn.get(dn.size() - 1));
  }catch (InvalidNameException e) {
      System.out.println(e.getMessage());
  }
}


来源:https://stackoverflow.com/questions/5800896/how-to-parse-security-certificate-subcomponents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!