0
I need to sign a string with a digital certificate.
However, when passing through the line that searches for the private key, the variable rsa
is getting the NULL value, falling into the if
and causing the program not to continue its execution.
I couldn’t find the reason for this. Follow the code in C#:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
static public string assinar(X509Certificate2 cert, String sAssinatura)
{
try
{
//recebe o certificado e a string a ser assinada
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
// Pega a chave privada do certificado digital
if (cert.HasPrivateKey) // Até aqui OK
{
rsa = cert.PrivateKey as RSACryptoServiceProvider; // AQUI ESTÁ O PROBLEMA! "rsa" FICA null
if (rsa == null)
{
// ESTÁ CAINDO AQUI DENTRO!
Log.Gravar("RSA deu 'NULO' ao acessar a Chave Privada do Certificado!");
}
}
else
{
Log.Gravar("Não foi possível acessar Chave Privada do Certificado");
}
// ............... resto do código ............. //
}
catch (System.Exception exc)
{
return exc.Message;
}
}
The code looks ok. Which certificate you are using?
– Rafa C.
Common certificate, v3, installed on machine, with extension pfx
– Rodrigo Tognin