我試圖使用證書私鑰解密一些數據。當證書安裝在本地計算機上時(我正在使用自簽名證書進行測試並且擁有證書的私鑰),這一切都可以正常工作,但是當我嘗試從使用相同代碼的遠程計算機訪問私鑰時,我得到「鍵盤不存在」異常。當從遠程機器讀取私鑰時「System.Security.Cryptography.CryptographicException:密鑰集不存在」
我正在使用控制檯應用程序進行測試,並且確保我的ID對遠程服務器上的私鑰具有讀取權限。下面是我使用的示例代碼:
var store = new X509Store(@"\\server1\My", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var result = store.Certificates.Find(X509FindType.FindBySubjectName, "server1.test.com", false);
var certificate = result[0];
store.Close();
//This succeeds from both local and remote server
var rsaPublic = (RSACryptoServiceProvider)certificate.PublicKey.Key;
//This succeeds from local, but fails from remote server
var rsaPrivate = (RSACryptoServiceProvider)certificate.PrivateKey;
這裏是異常調用堆棧
Unhandled Exception: System.Security.Cryptography.CryptographicException: Keyset does not exist
at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
at RsaPoc.Program.Main(String[] args)
我發現在SO一個similar懸而未決的問題,但它是使用非託管代碼,而我我正在使用託管API,但兩者似乎都有相同的根本原因。