2012-07-28 55 views
3

我正在使用SignedXML類進行rsa-sha256 xml簽名。但問題是我需要改變CSP來支持sha256。如何更改RSACryptoServiceProvider的CSP參數

這就是我如何選擇證書,

public X509Certificate2 GetCertificateFromStore() 
     { 
      X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser); 
      st.Open(OpenFlags.ReadOnly); 
      X509Certificate2Collection col = st.Certificates.Find(X509FindType.FindByTimeValid, (object)DateTime.Now, false); 

      X509Certificate2 x509Certificate =null; 
      X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificate", "Select single certificate to sign", X509SelectionFlag.SingleSelection); 
      if (sel.Count > 0) 
      { 
       X509Certificate2Enumerator en = sel.GetEnumerator(); 
       en.MoveNext(); 
       x509Certificate = en.Current; 
      } 
      st.Close(); 
      //x509Certificate.s 
      return x509Certificate; 
     } 

這是我正在試圖改變CSP參數。

byte[] privateKeyBlob; 
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); 
      rsa = cert.PrivateKey as RSACryptoServiceProvider; 
      try 
      { 
       privateKeyBlob = rsa.ExportCspBlob(true); 
      } 
      catch 
      { 
       throw new ApplicationException("Private key fails to export"); 
      } 
      // To use the RSA-SHA256 the CryptoAPI needs to select a special CSP: Microsoft Enhanced RSA and AES Cryptographic Provider 
      // By reinstantiating a CSP of type 24 we ensure that we get the right CSP. 
      CspParameters cp = new CspParameters(24); 
      rsa = new RSACryptoServiceProvider(cp); 
      rsa.ImportCspBlob(privateKeyBlob); 


      signer.SigningKey = rsa; 
      signer.KeyInfo = getKeyInfo(signer, cert); 

問題是我使用USB設備令牌,我懷疑私鑰是不可導出的。在導出時拋出一個錯誤'密鑰在指定狀態下無效。'。

任何人都可以幫助如何做到這一點?

+0

哪一行是異常拋出? – craig1231 2012-07-28 09:59:55

+0

這一行privateKeyBlob = rsa.ExportCspBlob(true); – Matt 2012-07-28 10:16:01

+0

是http://stackoverflow.com/q/10673146/589259有幫助嗎? – 2012-07-28 11:50:56

回答

0

如果有人對我的解決方案感興趣,我最終將使用另一個新版本的第三方CSP。我使用的CSP版本是舊版本,我切換到新版本。現在簽署工作。謝謝你的幫助。