Pergunta

Eu uso iTextSharp para assinar um arquivo PDF. Mas Adobe Reader não pode verificar a minha assinatura. Eu uso SHA-2 certificado de teste (eu tentei também SHA-1) gerado pela autoridade de certificação. Eu instalei o certificado raiz para certificados de teste desta autoridade.

public static void SignHashed(X509Certificate2 card, Stream input, Stream output) {
    Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
    Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) };

    PdfReader reader = new PdfReader(input);
    PdfStamper stp = PdfStamper.CreateSignature(reader, output, '\0');
    PdfSignatureAppearance sap = stp.SignatureAppearance;
    sap.SignDate = DateTime.Now;
    sap.SetCrypto(null, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    sap.Reason = "Testování";
    sap.Location = "Praha";
    sap.Acro6Layers = true;
    sap.Render = PdfSignatureAppearance.SignatureRender.GraphicAndDescription;
    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
    dic.Date = new PdfDate(sap.SignDate);
    dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
    if (sap.Reason != null) dic.Reason = sap.Reason;
    if (sap.Location != null) dic.Location = sap.Location;
    sap.CryptoDictionary = dic;
    int csize = 4000;
    Hashtable exc = new Hashtable();
    exc[PdfName.CONTENTS] = csize * 2 + 2;
    sap.PreClose(exc);

    System.Security.Cryptography.HashAlgorithm sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

    Stream s = sap.RangeStream;
    int read = 0;
    byte[] buff = new byte[8192];
    while ((read = s.Read(buff, 0, 8192)) > 0) {
        sha.TransformBlock(buff, 0, read, buff, 0);
    }
    sha.TransformFinalBlock(buff, 0, 0);
    byte[] pk = SignMsg(sha.Hash, card, false);

    byte[] outc = new byte[csize];

    PdfDictionary dic2 = new PdfDictionary();

    Array.Copy(pk, 0, outc, 0, pk.Length);

    dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
    sap.Close(dic2);
}

Alguém sabe melhor solução para assinar um PDF?

Foi útil?

Solução

Adobe Reader não pode verificar o sinal, porque necessidade de importar a cadeia de CA para o Adobe Reader no menu Advanced, opção "Gerenciar identidades confiáveis". Boa sorte!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top