我正在尝试使用代码将证书安装到WShttpBinding,下面的代码显示了我正在尝试的操作,
public static void InstallCertificate(X509Certificate2 cert,List<string> appPools = null)
{
try
{
bool certificate_exists = false;
using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(
X509FindType.FindByThumbprint,
cert.Thumbprint,
false);
if (certificates != null && certificates.Count > 0)
{
certificate_exists = true;
}
}
if (!certificate_exists)
{
using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert); //where cert is an X509Certificate object
int indexInStore = store.Certificates.IndexOf(cert);
cert = store.Certificates[indexInStore];
appPools?.ForEach(x =>
{
AddAccessToCertificate(cert, x);
});
}
}
}
catch (Exception ex)
{
throw new WriteAppSettingEx($"Could not install provided supplied certificate");
}
}
private static void AddAccessToCertificate(X509Certificate2 cert, string user)
{
RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
if (rsa != null)
{
string keyfilepath =
FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName);
FileInfo file = new FileInfo(keyfilepath + "\\" +
rsa.CspKeyContainerInfo.UniqueKeyContainerName);
FileSecurity fs = file.GetAccessControl();
NTAccount account = new NTAccount(user);
fs.AddAccessRule(new FileSystemAccessRule(account,
FileSystemRights.FullControl, AccessControlType.Allow));
file.SetAccessControl(fs);
}
}
该代码有效,只是直到之后我无法访问私钥
然后,我可以从IIS应用程序池中访问密钥,就实现的内容而言,是否缺少一些代码?我使用的是.NET 4.6,如果不执行上述步骤,则会得到一个不存在的密钥集,这表明我的应用程序池无法访问证书私钥。