1 回答

TA貢獻1712條經(jīng)驗 獲得超3個贊
// Attempt #1
CspParameters parameters = new CspParameters();
parameters.KeyContainerName = importedKeyName;
var rsaKey = new RSACryptoServiceProvider(parameters);
certificate.PrivateKey = rsaKey; // public key doesn't match the private key
CAPI(CspParameters 背后的庫)在 Windows 7 或 8.1 上根本無法理解 CNG 中的鍵;它(理論上)在 10 上支持它,但您肯定必須告訴它密鑰位于 CNG (CspParameters.ProviderName) 中。
此處的代碼在“Microsoft RSA 和 AES 增強型加密服務(wù)提供程序”中使用 ProviderType 24 創(chuàng)建了一個新的 CAPI 密鑰,該密鑰恰好與您的 CNG 密鑰具有相同的本地密鑰名稱。
您沒有指定標(biāo)志 UseExistingOnly,并且該密鑰不存在,所以它創(chuàng)建了一個新的……這就是公鑰與證書中的內(nèi)容不匹配的原因。
// Attempt #2
var rsaCngKey = new RSACng(CngKey.Open(importedKeyName));
certificate.PrivateKey = rsaCngKey; // Only asymmetric keys that implement ICspAsymmetricAlgorithm are supported.
該PrivateKey屬性只支持 CAPI,無論是 get 還是 set。該集合使用起來非常危險,因為它不會修改證書對象,它會修改 Windows 證書存儲系統(tǒng)中證書的狀態(tài)……這意味著它還會影響在同一對象上運行的任何其他現(xiàn)在或?qū)淼膶ο?Windows) 證書。
// Attempt #3
certificate.PrivateKey = null;
X509Certificate2 certWithKey = certificate.CopyWithPrivateKey(rsaKey); // The provided key does not match the public key for this certificate.
這是從嘗試 1 創(chuàng)建的相同的新隨機密鑰。
如果您刪除嘗試 1,然后合并 2 和 3,您應(yīng)該以
var rsaCngKey = new RSACng(CngKey.Open(importedKeyName));
X509Certificate2 certWithKey = certificate.CopyWithPrivateKey(rsaCngKey);
這應(yīng)該有效。(如果您已經(jīng)將證書導(dǎo)入到證書存儲中,您可以只添加certWithKey到證書存儲中,這將具有與“每個人都突然知道這個”更新更改相同的更新更改cert.set_PrivateKey,除了您詢問證書存儲更明顯進行更改)
- 1 回答
- 0 關(guān)注
- 348 瀏覽
添加回答
舉報