今日測試時,在下列第二行一直發生System.Security.Cryptography.CryptographicException: Key not valid for use in specified state 的錯誤。中文訊息是「機碼用在特定狀態時無效」
RSACryptoServiceProvider provider = cert.PrivateKey as RSACryptoServiceProvider;
RSAParameters signPrivateKey = provider.ExportParameters(true);
沒看過耶!查了 Google 大神也是無效。
結果,重匯 pfx (即有私鑰的憑證) 就好了?
真是怪
今日證實,是程式寫錯了。
使用provider.ExportParameters(true),即將私鑰匯出,這是不對的。
我只需要將私鑰拿來簽章即可。
如下
XmlDocument doc = new XmlDocument(); doc.LoadXml(origXml); //匯入私鑰 X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbPrint, true); if (certs.Count == 0) throw new CryptographicException("The certificate could not be found."); X509Certificate2 cert = certs[0]; RSACryptoServiceProvider provider = cert.PrivateKey as RSACryptoServiceProvider; SignedXml signXml = new SignedXml(doc); signXml.SigningKey = provider;
沒有留言:
張貼留言