我有一些代码需要使用X509证书信息。我已经下载了一个样本:
const string CertWithoutPrivateKey = "MII....";
const string CertWithPrivateKey = "MII...";
public static SecurityToken GetSigningToken(bool includePrivateKey)
{
X509Certificate2 cert = null;
if (includePrivateKey)
{
cert = new X509Certificate2(
Convert.FromBase64String(CertWithPrivateKey),
"pw", X509KeyStorageFlags.PersistKeySet);
}
else
{
cert = new X509Certificate2(
Convert.FromBase64String(CertWithoutPrivateKey));
}
return cert;
}
代码需要能够使用私钥获取证书。 Saml2AuthenticationModule(来自SAML 2.0协议的WIF扩展)依赖此私钥来解密从SAML身份提供程序发送的信息。
我对证书或加密知之甚少,但在我看来,将证书硬编码到类中是不安全的。
那么,我的代码应如何使用私钥检索证书? Afaik,此代码仅在应用启动时运行一次(因此也可能在应用池回收后运行)。
我可以:
还有其他选择吗?在这种情况下最合适的是什么?
答案 0 :(得分:2)
带或不带私钥的证书可以保存到用户或计算机的X509商店。这已经具有内置的Windows安全性,应该足够了。您可以将mmc
与证书管理单元一起使用,以将证书添加到商店并对其进行管理。
对证书的引用(例如,其名称或缩略图)可以保存到配置文件中并用于检索证书。检索可能如下所示:
public static X509Certificate2 GetCertificate(string name)
{
try
{
X509Store store = new X509Store (StoreLocation.LocalMachine);
X509Certificate2Collection collection = store.Certificates;
foreach (X509Certificate2 x509 in collection)
{
if (x509.FriendlyName.Equals(name))
{
return x509;
}
}
}
finally
{
store.Close();
}
return null;
}
在集合上使用Find
是搜索证书的另一种(更简洁)方式。
答案 1 :(得分:1)
我不确定WIF是如何做到的(您可以使用Reflector查看它与证书存储区交互的内部结构),但听起来您在IIS中托管的应用程序中使用WIF。如果是这种情况, WIF应该为您处理所有证书互动。您只需确保设置以下内容: