[英]How to import programmally a private key in the local machine keystore?
如何以编程方式在本地计算机密钥库中导入私钥?
实际上,我正在测试以下代码:
private static void InstallCertificate(string certificatePath, string certificatePassword, StoreName store) {
try {
var serviceRuntimeUserCertificateStore = new X509Store(store, StoreLocation.LocalMachine);
serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);
X509Certificate2 cert;
try {
cert = new X509Certificate2(certificatePath, certificatePassword);
} catch(Exception ex) {
Console.WriteLine("Failed to load certificate " + certificatePath);
throw new DataException("Certificate appeared to load successfully but also seems to be null.", ex);
}
serviceRuntimeUserCertificateStore.Add(cert);
serviceRuntimeUserCertificateStore.Close();
} catch(Exception) {
Console.WriteLine("Failed to install {0}. Check the certificate index entry and verify the certificate file exists.", certificatePath);
}
}
所有尝试获取NetworkService令牌的尝试都失败了。 此处的代码不适用于管理员权限。
上面的代码将私钥导入到本地计算机的当前用户instat中。 我该怎么办?
MSDN有一个解决方案 。 只需添加一个标志X509KeyStorageFlags.MachineKeySet
,它就可以正常运行:
cert = new X509Certificate2(certificatePath,
certificatePassword,
X509KeyStorageFlags.MachineKeySet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.