views:

11

answers:

0

I have the following .Net code (asp.net) 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; 
 } 

} 

EDIT: Perhaps problems with identity in AppPool. The user that install the certificate in LocalMachine Store must be identity of AppPool of WebSite, and are in IIS_WPG group.