我在使用证书时遇到问题。我需要从商店中提取证书(P12),使用给定的密码检索其私钥,使用SHA1算法创建私钥的数字签名,最后将签名的签名转换为base64格式。我使用以下代码,但它完全陷入困境:
private string GetCertificado(string strNCertif)
{
//Certificado RSA PKCS#12 (.P12)
string strPKI = string.Empty;
X509Store stoLocalizCertif = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
stoLocalizCertif.Open(OpenFlags.ReadOnly);
X509Certificate2Collection Resultado =
stoLocalizCertif.Certificates.Find(X509FindType.FindByIssuerDistinguishedName, strNCertif, true);
if (!(Resultado.Count.Equals(0)))
{
X509Certificate2 objCertificado = Resultado[0];
var objChvPrv = objCertificado.PrivateKey as RSACryptoServiceProvider;
byte[] bytCertifValor = Resultado.Export(X509ContentType.Pkcs12, "password"); //-> Key not valid for use in specified state.
byte[] bytAssinatura = objChvPrv.SignData(bytCertifValor, new SHA1Managed());
byte[] bytCodific = SHA1Managed.Create().ComputeHash(bytCertifValor);
RSAPKCS1SignatureFormatter objFormata = new RSAPKCS1SignatureFormatter(objCertificado.PrivateKey);
objFormata.SetHashAlgorithm("SHA1");
bytAssinatura = objFormata.CreateSignature(bytCodific);
strPKI = Convert.ToBase64String(bytAssinatura);
stoLocalizCertif.Close();
}
return strPKI;
}
有什么想法?提前谢谢。