验证证书和安装证书
protected void Page_Load(object sender, EventArgs e)
{
if (!isExsitCertificate(StoreLocation.CurrentUser, StoreName.Root, X509FindType.FindByIssuerName, "CN=颁发者名称"))
{
//从证书文件载入证书,如果含有私钥的,需要提供保存证书时设置的密码
string path = Server.MapPath(@"") + "\\scriptx\\Root.cer";
X509Certificate2 myX509Certificate2 = new X509Certificate2(
path, //证书路径
"", //证书的私钥保护密码
X509KeyStorageFlags.Exportable //表示此证书的私钥以后还可以导出
);
X509Store Rootstore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
Rootstore.Open(OpenFlags.ReadWrite);
Rootstore.Add(myX509Certificate2);
Rootstore.Close();
}
}
//校验证书是否已存在
public bool isExsitCertificate(
StoreLocation location, StoreName name,
X509FindType findType, string findValue)
{
bool isExist = false;
X509Store store = new X509Store(name, location);
try
{
// create and open store for read-only access
store.Open(OpenFlags.ReadOnly);
// search store
foreach (X509Certificate2 singelCertificate in store.Certificates)
{
if (singelCertificate.IssuerName.Name == findValue)
{
isExist = true;
return isExist;
}
}
}
catch { }
finally
{
store.Close();
}
return isExist;
}
{
if (!isExsitCertificate(StoreLocation.CurrentUser, StoreName.Root, X509FindType.FindByIssuerName, "CN=颁发者名称"))
{
//从证书文件载入证书,如果含有私钥的,需要提供保存证书时设置的密码
string path = Server.MapPath(@"") + "\\scriptx\\Root.cer";
X509Certificate2 myX509Certificate2 = new X509Certificate2(
path, //证书路径
"", //证书的私钥保护密码
X509KeyStorageFlags.Exportable //表示此证书的私钥以后还可以导出
);
X509Store Rootstore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
Rootstore.Open(OpenFlags.ReadWrite);
Rootstore.Add(myX509Certificate2);
Rootstore.Close();
}
}
//校验证书是否已存在
public bool isExsitCertificate(
StoreLocation location, StoreName name,
X509FindType findType, string findValue)
{
bool isExist = false;
X509Store store = new X509Store(name, location);
try
{
// create and open store for read-only access
store.Open(OpenFlags.ReadOnly);
// search store
foreach (X509Certificate2 singelCertificate in store.Certificates)
{
if (singelCertificate.IssuerName.Name == findValue)
{
isExist = true;
return isExist;
}
}
}
catch { }
finally
{
store.Close();
}
return isExist;
}