2013-12-19 70 views
2

一直在搜索網絡和博客並在其中查找碎片,並試圖將它們放在一起以便能夠使用System.Security.Cryptography.X509Certificates對iTextSharp庫進行數字簽名。密鑰無法在指定狀態下使用CryptographicException與BouncyCastle

,我與它後面的下面的代碼號按鈕:

Dim m As New PdfManipulation 
    Dim store As New X509Store("MY", StoreLocation.CurrentUser) 
    store.Open(OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly) 

    Dim collection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection) 
    Dim fcollection As X509Certificate2Collection = CType(collection.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection) 
    Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection) 

    For Each x509 As X509Certificate2 In scollection 
     m.DigitallySignPdf("C:\Users\my\Desktop\populates.pdf", "C:\Users\my\Desktop\A.pdf", "topmostSubform[0].Page1[0].SignatureField1[0]", x509) 
    Next x509 

    store.Close() 

上面的代碼工作的,它打開了我的證書存儲,我選擇一個證書。然後它將證書傳遞給以下PdfManiuplation類進行簽名。

PdfManipulation代碼:

Public Class PdfManipulation 

Public Sub DigitallySignPdf(ByVal sourceDocument As String, _ 
          ByVal destinationPath As String, _ 
          ByVal fieldNameToSign As String, _ 
          ByVal signature As X509Certificate2) 

    Dim reader As New PdfReader(sourceDocument) 
    Using fout As New FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite) 
     Using stamper As PdfStamper = PdfStamper.CreateSignature(reader, fout, ControlChars.NullChar) 
      ' appearance 
      Dim appearance As PdfSignatureAppearance = stamper.SignatureAppearance 
      appearance.SetVisibleSignature(fieldNameToSign) 

      ' digital signature 
      Dim akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private 
      Dim es As IExternalSignature = New PrivateKeySignature(akp, "SHA-256") 
      Dim cp As New Org.BouncyCastle.X509.X509CertificateParser() 


      MakeSignature.SignDetached(appearance, es, New Org.BouncyCastle.X509.X509Certificate() {cp.ReadCertificate(signature.RawData)}, Nothing, Nothing, Nothing, 0, CryptoStandard.CMS) 

      stamper.Close() 

     End Using 
    End Using 

End Sub 

End Class 

時拋出異常。當它到達

Dim akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private 

多數民衆贊成。我選擇的證書是我在機器上籤署的所有證書,所以我知道這很好。任何幫助,爲什麼這會拋出這個錯誤將不勝感激,或指針在正確的方向。

而且,這裏是我的進口清單:

Imports System.Security.Cryptography 
Imports System.Security.Permissions 
Imports System.IO 
Imports System.Security.Cryptography.X509Certificates 
Imports iTextSharp.text.pdf.security 
Imports iTextSharp.text 
Imports iTextSharp.text.pdf 

,不得不添加引用:

System.Security 

堆棧跟蹤:

System.Security.Cryptography.CryptographicException was unhandled 
    HResult=-2146893813 
    Message=Key not valid for use in specified state. 

    Source=mscorlib 
    StackTrace: 
     at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) 
     at System.Security.Cryptography.Utils._ExportKey(SafeKeyHandle hKey, Int32 blobType, Object cspObject) 
     at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters) 
     at Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(RSA rsa) 
     at Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(AsymmetricAlgorithm privateKey) 
     at AccessRequest.PdfManipulation.DigitallySignPdf(String sourceDocument, String destinationPath, String fieldNameToSign, X509Certificate2 signature) in C:\PdfManipulation.vb:line 237 
     at Form.btnSubmit_Click(Object sender, EventArgs e) in C:\Form.vb:line 251 
     at System.Windows.Forms.Control.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnClick(EventArgs e) 
     at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
     at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
     at System.Windows.Forms.Control.WndProc(Message& m) 
     at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
     at System.Windows.Forms.Button.WndProc(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
     at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
     at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
     at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
     at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
     at System.Windows.Forms.Application.Run(ApplicationContext context) 
     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() 
     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() 
     at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) 
     at app.My.MyApplication.Main(String[] Args) in 11111.vb:line 81 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

而且經過進一步的測試和觀察通過IDE私鑰,我注意到

signature.privatekey.CspKeyContainerInfo.Exportable = False 

這可能是錯誤的原因,如果是這樣,如何使選定的證書導出?因爲我通過搜索看到的唯一事情實際上是創建一個新證書並將StorageFlag設置爲可導出,並且我不試圖創建新證書。我只是試圖使用選定的證書。

+0

感謝您在問題中積累的信息量,但也請包括堆棧跟蹤。 –

回答

3

該錯誤是由於私人證書是不是可導出的事實造成的。

我一直想知道,通過我所有的測試,爲什麼我沒有被提示,即使我的智能卡針被選爲我的智能卡針。這導致我最終選擇了一個我知道的證書,不會要求銷售商和中提琴,PDF已導出並已簽名。即使通過代碼走到查看證書專用密鑰財產,這一次讀

signature.privatekey.CspKeyContainerInfo.Exportable = True 

並最終匹配的另一種形式我發現的,其表示,他們通過將私有密鑰導出固定到自己的錯誤。現在我所要做的就是弄清楚如何使用應該向我索要我的密碼的證書。如果我發現這個問題,我會回到這裏。

相關問題