iText C#MakeSignature.SignDetached抛出NullReference异常

时间:2014-05-08 09:52:34

标签: c# itext

我们使用C#示例C2_01_SignHelloWorld成功签署PDF文档:

http://sourceforge.net/p/itextsharp/code/HEAD/tree/tutorial/signatures/chapter2/C2_01_SignHelloWorld/C2_01_SignHelloWorld.cs#l21

对于我们签署的几乎所有PDF,这都可以。但是,只要有一个或多个附件,MakeSignature.SignDetached就会抛出NullReference异常。

有人想知道为什么会这样吗?

谢谢!

以下是我们的代码段:

PdfReader reader = new PdfReader(pdfFileName);
PdfSignatureAppearance signatureAppearance;
String pdfFileNameDest = pdfFileName.Substring(0, pdfFileName.LastIndexOf('.')) + "-signed" + pdfFileName.Substring(pdfFileName.LastIndexOf('.'));

FileStream fileStream = new FileStream(certFileName, FileMode.Open);
FileStream fileStreamDest = new FileStream(pdfFileNameDest, FileMode.Create);
Pkcs12Store store = new Pkcs12Store(fileStream, certPassword.ToCharArray());
String alias = "";
ICollection<X509Certificate> chain = new List<X509Certificate>();

try
{
    // Search private key
    foreach (string al in store.Aliases)
        if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
        {
            alias = al;
            break;
        }

    AsymmetricKeyEntry pk = store.GetKey(alias);
    foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
        chain.Add(c.Certificate);

    RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

    PdfStamper stamper = PdfStamper.CreateSignature(reader, fileStreamDest, '\0');

    signatureAppearance = stamper.SignatureAppearance;
    signatureAppearance.Reason = "Because we need to sign it";
    signatureAppearance.Contact = "We";
    signatureAppearance.Location = "Server";

    IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);

    MakeSignature.SignDetached(signatureAppearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
    signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null);

    stamper.Close();
}
catch (Exception ex)
{
    MessageBox.Show("Exception: " + ex.ToString());
}

0 个答案:

没有答案