[英]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.