首页 > 解决方案 > 使用 iTextSharp 向 PDF 添加数字签名 - 智能卡证书(PIN 保护)

问题描述

我使用以下代码签署 PDF 文档,但我总是得到一个无效的证书。

private void SignWithThisCert(X509Certificate2 cert)
        {
string SourcePdfFileName = Application.StartupPath + @"\Document.pdf";
string DestPdfFileName = Application.StartupPath + @"\Document.Signed.pdf";
Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };

IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA256");
PdfReader pdfReader = new PdfReader(SourcePdfFileName);
FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create);  //the output pdf file
PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

signatureAppearance.Reason = "Safe Document";
signatureAppearance.Location = "My place";            

signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
//MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES);
pdfStamper.Close();
MessageBox.Show("Done");

}

然后我就调用这个方法:

//Sign from SmartCard
//note : ProviderName and KeyContainerName can be found with the dos command : CertUtil -ScInfo
string ProviderName = "cv act sc/interface CSP";
string KeyContainerName = "12345e02a1dcb12ece12345f0e203c093eb2f0ef";
string PinCode = "MYPINCODE";
if (PinCode != "")
{
    //if pin code is set then no windows form will popup to ask it
    SecureString pwd = GetSecurePin(PinCode);
    CspParameters csp = new CspParameters(1,
                    ProviderName,
            KeyContainerName,
            new System.Security.AccessControl.CryptoKeySecurity(),
            pwd);
    try
    {
        RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp);
                // the pin code will be cached for next access to the smart card
    }
    catch (Exception ex)
    {
            MessageBox.Show("Crypto error: " + ex.Message);
                return;
    }
}
var cert = Helper.GetCertBySubject("cert subject here");
SignWithThisCert(cert);

它在 PDF 文档上签名,但是当我在阅读器中打开它时,它说证书无效。

我正在使用带有不可导出私钥的 PIN 保护智能卡 - PKCS#12

我可能需要使用PK吗?

太感谢了

标签: c#pdfitextsmartcard

解决方案


推荐阅读