none
“Cannot find the certificate and private key for decryption” for Certificate pfx pkcs#12 with private key

    Question

  • I have the following .Net code for sign using client certificate.


    I have client certificate stored under local computer and not the current user.

    The client certificate  is pfx pkcs#12 and has private key

    Imported private key are NOT marked as exportable.

    my private key in client certificate protected  by password.


    On the last line above, I get the error "Cannot find the certificate
    and private key for decryption ".

    It looks like the Private Key is not accessible when using my code.

    Is there anyway for me to associate the private key to my client certificate ? Any suggestions ?

     

        public void FirmarConCertificado(string nombreCertificado, X509Certificate2 certificate)
        {
            try
            {
         var mensaje = "Datos de prueba";
                        System.Text.Encoding enc = System.Text.Encoding.Default;
                        byte[] data = enc.GetBytes(mensaje);
        
                        var contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(data);
                        var signedCms = new System.Security.Cryptography.Pkcs.SignedCms(contentInfo, true);
        
                        var cmsSigner = new System.Security.Cryptography.Pkcs.CmsSigner(certificate);
        
                        //  Sign the CMS/PKCS #7 message
                        signedCms.ComputeSignature(cmsSigner);  // <<<<<<< FAILS HERE
        
                        //  Encode the CMS/PKCS #7 message
                       var ret = Convert.ToBase64String(signedCms.Encode());
        
         Message.Text += "Firmado con Certificado " + nombreCertificado + " encontrado en " + StoreLocation.LocalMachine;
         }
         catch (Exception ex)
         {
         Message.Text = "Error al firmar con certificado: " + ex.ToString();
         Message.Text += "<br /><br />InnerException: " + ex.InnerException;
         }
        
        }

     


    Should "Hi", "Thanks" and taglines and salutations be removed from posts? http://meta.stackoverflow.com/questions/2950/should-hi-thanks-and-taglines-and-salutations-be-removed-from-posts
    Monday, October 18, 2010 7:41 AM

All replies

  • Hi Alhambra,

     

    Thank you for your post.

     

    This exception is a general issue.

    Regarding information, I suspected that you might check your certification file is right or not.

    The program might not find your certification or format of private key isn’t right.

     

    CHEERS,

    Larcolais


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, October 20, 2010 7:50 AM