Java如何从HttpRequest中的SSL证书中提取“发布给”或用户?

时间:2012-11-02 17:33:19

标签: java ssl httprequest

在Java中如何从HttpRequest中的SSL证书中提取“发给”或用户?

我正在与之合作:

 Object certChain = request
    .getAttribute("javax.servlet.request.X509Certificate");
if (certChain != null)
{
  X509Certificate certs[] = (X509Certificate[]) certChain;
  X509Certificate cert = certs[0];
  String user = cert.getSubjectDN().getName();
}

2 个答案:

答案 0 :(得分:3)

这是在httprequest中提取证书的“Issued To”又名主题的代码,

import java.security.cert.X509Certificate;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;

X509Certificate[] certs = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
if ((certs == null) || (certs.length == 0)) {
   return null;
}

String name = certs[0].getSubjectX500Principal().getName(); // if you are looking for issuer then use cert[0].getIssuerX500Principal().getName();
LdapName ldapName = null;
try {
   ldapName = new LdapName(name);
} catch (InvalidNameException e) {
   throw new RuntimeException(e);
}

for (Rdn rdn : ldapName.getRdns()) {
   String type = rdn.getType();
   if ("CN".equals(type)) { 
        String issuedTo = (String)rdn.getValue();
   }
}

JDK 6在本地的rt.jar中有API getSubjectX500Prinicpal(),不确定以前的版本, enter image description here

答案 1 :(得分:2)

getSubjectDN()不应再使用了。

  

诋毁,取而代之的是getSubjectX500Principal()。

所以使用:

cert[0].getSubjectX500Principal().getName();

以下是getSubjectX500Principal()的JavaDoc。