最近涉及到项目中有采用.NET作为开发平台,因为之前对.NET的了解并不清楚,所以证书的部分信息读取可以,但在国家定义的扩展信息的内容时没有成功。最近重新看了微软的说明以及从网上找了部分信息,整理出来了读取证书扩展域信息的方法。
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Security.Cryptography.X509Certificates;
namespace Cert
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
X509Certificate cs = new X509Certificate(Request.ClientCertificate.Certificate);
X509Certificate2 x509 = new X509Certificate2(cs);
//税务扩展域信息读取开始
X509Extension ext = x509.Extensions["1.2.86.11.7.5"];
Byte[] byteArray = ext.RawData;
String nsrsbh = System.Text.Encoding.ASCII.GetString(byteArray);
nsrsbh = nsrsbh.Substring(3).Trim();//14位纳税人识别号
//税务扩展域信息读取结束
String tempSubject="";//完整的用户DN
String CN = "";//用户名称
String SN = "";//数字证书序列号
tempSubject = cs.Subject.ToString();
int i = tempSubject.IndexOf("CN=");
int k = tempSubject.IndexOf(',', i);
if (k < 0)
{
CN = tempSubject.Substring(i).Trim();
}
else
{
CN = tempSubject.Substring(i + 3, k).Trim();
}
SN = cs.GetSerialNumberString();//数字证书唯一序列号
Response.Write("纳税人识别号 = " + nsrsbh + "<br>");
Response.Write("用户名称 = " + CN + "<br>");
Response.Write("数字证书唯一序列号 = " + SN + "<br>");
Response.Write("证书称 = " + tempSubject + "<br>");
}
}
}