我在 C # Windows 窗体中创建了一个测试项目,并集成了获取文档并使用证书对其进行签名的方法,但是当我调用DotNetUtils.GetKeyPair()
时,它返回"密钥集不存在"。我发现我必须将证书"安装"为"可导出",但是有没有办法不删除并重新导入证书?有什么方法可以让它在我现在的情况下工作吗? 这是我的代码:
private byte[] SignDocumentWithCertificate(byte[] myPdf, X509Certificate2 myCertificate)
{
PdfReader reader = new PdfReader(myPdf);
using (MemoryStream msOutput = new MemoryStream())
{
PdfStamper stamper = PdfStamper.CreateSignature(reader, msOutput, ' ');
PdfSignatureAppearance sap = stamper.SignatureAppearance;
sap.Reason = "Documento firmato con certificato '" + myCertificate.FriendlyName.ToString() + "' .";
sap.Location = "Italy";
X509Certificate2 signatureCert = new X509Certificate2(myCertificate);
var pk = DotNetUtils.GetKeyPair(signatureCert.PrivateKey).Private; //NON FUNZIONA, VA IN EXCEPTION
BcX509.X509Certificate bcCert = DotNetUtils.FromX509Certificate(signatureCert);
var chain = new List<BcX509.X509Certificate> { bcCert };
IExternalSignature signature = new PrivateKeySignature(pk, "SHA-256");
MakeSignature.SignDetached(sap, signature, chain, null, null, null, 0, CryptoStandard.CMS);
return msOutput.ToArray();
}
}
@mkl 最后,根据您的建议,我使用此代码搜索并解决了:
private byte[] SignDocumentWithCertificate_VCertificate(byte[] myPdf, X509Certificate2 myCertificate)
{
using (MemoryStream msOutput = new MemoryStream())
{
PdfReader Reader = new PdfReader(myPdf);
PdfStamper Stamper = PdfStamper.CreateSignature(Reader, msOutput, ' ');
PdfSignatureAppearance SAP = Stamper.SignatureAppearance;
BcX509.X509Certificate BouncyCertificate = DotNetUtils.FromX509Certificate(myCertificate);
var chain = new List<BcX509.X509Certificate> { BouncyCertificate };
IExternalSignature ES = new X509Certificate2Signature(myCertificate, DigestAlgorithms.SHA1);
MakeSignature.SignDetached(SAP, ES, chain, null, null, null, 0, CryptoStandard.CMS);
Stamper.Close();
Reader.Close();
return msOutput.ToArray();
}
}
我使用证书而不是私钥对文档进行了签名。 多谢。