1

I have this code which serves to sign a file:

        private void Sign(String cFile, string cPin)
        {

        X509Certificate2 oCertificato = null;

        X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        x509Store.Open(OpenFlags.ReadOnly);

        X509Certificate2Collection col = x509Store.Certificates;
        X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "", "", X509SelectionFlag.SingleSelection);

        if (sel.Count > 0)
        {
            X509Certificate2Enumerator en = sel.GetEnumerator();
            en.MoveNext();
            oCertificato = en.Current;
        }

        x509Store.Close();

        System.Security.SecureString SecurePIN = new System.Security.SecureString();
        foreach (char ch in cPin)
        { SecurePIN.AppendChar(ch); }
        /////////LINE OF ERROR
        **var rsa = (RSACryptoServiceProvider)oCertificato.PrivateKey;**
        /////////////////////////////////
        [CUT CODE HERE...]
        return;
    }

At the highlighted line I get this error:

Incorrect initialization performed by a provider DLL. (Translated from Italian). Error level: System.Security.Cryptography.CryptographicException. Until a few days ago everything was fine, maybe it's because of some Windows 10 update, because the error does it even on the customers' computers, but I don't understand how to solve it.

This is the complete Stacktrace:

    in System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
in System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
in System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
in System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
in System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
in Firmapdf.Firmaref.Sign(String cFile, String cPin) in D:\DOTNET\FirmaPDF\Firmaref.cs:riga 325
in Firmapdf.Firmaref.btConferma_Click(Object sender, EventArgs e) in D:\DOTNET\FirmaPDF\Firmaref.cs:riga 65
in System.Windows.Forms.Control.OnClick(EventArgs e)
in System.Windows.Forms.Button.OnClick(EventArgs e)
in System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
in System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
in System.Windows.Forms.Control.WndProc(Message& m)
in System.Windows.Forms.ButtonBase.WndProc(Message& m)
in System.Windows.Forms.Button.WndProc(Message& m)
in System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
in System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
in System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
in System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
in System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
in System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
in System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
in System.Windows.Forms.Application.Run(Form mainForm)
in Firmapdf.Program.Main() in D:\DOTNET\FirmaPDF\Program.cs:riga 35
in System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
in System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ThreadHelper.ThreadStart()
zaitsman
  • 8,984
  • 6
  • 47
  • 79
Frank
  • 69
  • 15
  • 1
    Could you post the whole stacktrace? – dreijntjens Sep 16 '19 at 17:18
  • Does your certificate have the private key? Does user have access to manage the private key? Has the Group Policy changed? – zaitsman Sep 17 '19 at 01:35
  • @zaitsman, The certificate has a private key and no policy has changed, unless Microsoft has done so with its updates. – Frank Sep 17 '19 at 06:25
  • Check the Security and System logs in Event Viewer, look for SChannel errors. – zaitsman Sep 17 '19 at 06:31
  • @dreijntjens, I added the complete stacktrace to the end of my post. – Frank Sep 17 '19 at 06:35
  • 1
    Also add the full error-message. This issue looks the same: https://stackoverflow.com/questions/6178711/exception-when-trying-to-read-a-privatekey-from-windows-certstore but i'm not totally sure since I don't know the error message itself – dreijntjens Sep 17 '19 at 06:40
  • @zaitsman, Unfortunately, I can not find anything in the event log. – Frank Sep 17 '19 at 06:49
  • The user does not have permissions to the Private Key. For example, try this: https://stackoverflow.com/questions/6178711/exception-when-trying-to-read-a-privatekey-from-windows-certstore – zaitsman Sep 17 '19 at 06:51
  • Since this is user store, you can press Win+r, type `certmgr.msc`, find your cert, right click - All Tasks - Manage Private keys, add permissions to your user – zaitsman Sep 17 '19 at 06:52
  • @zaitsman I have only these choices: Open - Request certificate with new key - Renew certificate with new key - Export. Also I just did a test on a computer with Windows 10 not updated and everything works perfectly! Obviously the fault lies with Microsoft, but I don't know what to do to solve the problem. – Frank Sep 17 '19 at 07:09
  • So that means the user you are using to open it does not itself have rights to manage keys. Try export and re-import the cert. – zaitsman Sep 17 '19 at 07:10
  • @zaitsman, Already tried, it doesn't work, also because the certificate is on a Smartcard and is automatically imported at each insertion. – Frank Sep 17 '19 at 07:19
  • @Frank ... ‍♂️ you really should've mentioned that the cert is on the SmartCard. You should probably look into your specific SmartCard issues with Windows 10... – zaitsman Sep 17 '19 at 07:46
  • @zaitsman Sorry for the forgetfulness, but the problems are not of my Smartcard because it also happens with those of my customer (as I said in my post), the problem is the updates of Windows 10, now I'm trying to figure out which is what creates this disaster . – Frank Sep 17 '19 at 07:53
  • So you're not experiencing sth like this then? https://www.dell.com/community/Latitude/Smartcard-reader-breaks-on-7390-DDPE-w-Win-10-1803/td-p/6188188 – zaitsman Sep 17 '19 at 08:00
  • @zaitsman Not exactly, that is a reader problem, mine is a certificate problem, the reader works perfectly even with other cards of different types. I see the certificate correctly in the Windows Store, but for some reason I get the errors I described. – Frank Sep 17 '19 at 08:29
  • If certificate has associated private key, check this post on how you should access private key in .NET: https://stackoverflow.com/a/57874405/3997611. The way you are doing is very fragile nowadays since KSP usage is expanded. – Crypt32 Sep 17 '19 at 14:17
  • @Crypt32, Thanks, I tried but nothing changes, The problem, in my opinion, is in the windows store that doesn't handle the certificates in a Smartcard well. – Frank Sep 18 '19 at 07:02

0 Answers0