Quantcast

How sign a Pdf with Pades standard

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

How sign a Pdf with Pades standard

Piercarlo
This post has NOT been accepted by the mailing list yet.
Hi
I need to sign a PDF with PADES standard.
I'm using c# I I think to use ItextSharp with BoundyCastle c# combination.
Somebody can help to start ?

Best Regards

Piercarlo
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How sign a Pdf with Pades standard

Andreanta
This post has NOT been accepted by the mailing list yet.
This is pieces of my code to sign a pdf with cades, use the code from modified bouncycastle from forum msn.

The only strange think is that acrobat reader verify the signature but othet tools show digest problem.

If you have some ideas respond me

Ciao
Andrea


 private bool SignHashed(SignSettings settings)


        {
            bool retVal = false;

            X509Certificate2 card = SelectCertificateFromStore();

            if (card != null)
            {
                Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
                Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) };
                BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                Font font = new Font(helvetica, 8, Font.NORMAL);
                string cn = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
                //settings.SourceStream = WriteToPdf(settings.SourceStream, "firmato da " + cn, enTipoTimbro.Footer);
                MemoryStream m = new MemoryStream();
                PdfReader reader = new PdfReader(settings.SourceStream);
                PdfStamper stp = PdfStamper.CreateSignature(reader, m, '\0', null, true);
                stp.Writer.CloseStream = false;

                PdfSignatureAppearance sap = stp.SignatureAppearance;
                sap.SignDate = DateTime.Now;
                sap.SetCrypto(null, chain, null, null);
                sap.Reason = settings.Reason;
                sap.Location = settings.Location;
                sap.Acro6Layers = true;
                sap.Stamper.Writer.CloseStream = false;
                //ADOBE_PPKMS

                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;                
                Dictionary<PdfName, int> dic_ex = new Dictionary<PdfName, int>();
                dic_ex.Add(PdfName.CONTENTS, csize * 2 + 2);
                sap.PreClose(dic_ex);

                HashAlgorithm sha = new 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 = null;


                if (settings.Sign256)
                {
                    Debug.Print(ByteArrayToString(sha.Hash));  
                    Debug.Print(GetSHA1Hash(buff));
                 

                    pk = SignMessageSha256(sha.Hash, card);


                }
                else
                    pk = SignMessage(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);
                settings.DestinationStream = new MemoryStream(m.ToArray());
                retVal = true;
            }
            return retVal;
        }




 public byte[] SignSha256(byte[] data, X509Certificate2 certificate)
        {
            try
            {
                //Creo l'RSA dalla chiave privata del certificato
                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
                                // Converto il certificato da .Net a BC
                Org.BouncyCastle.X509.X509Certificate certBc = DotNetUtilities.FromX509Certificate(certificate);
                // preparo il CMS con i dati per realizzare la firma ed aggiungo la firma
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                //Aggiuingo tutti i dati per la firma                
                cms.AddSigner(rsa, certBc, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", HashCertificato(certificate), null);
             
                // Aggiungo il certificato pubblico di firma al pacchetto
                ArrayList certList = new ArrayList();
                certList.Add(certBc);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //Realizzo il pacchetto di firma
                CmsSignedData sigData = cms.Generate(new CmsProcessableByteArray(data), true);
                return sigData.GetEncoded();
            }
            catch (Exception exc)
            {
                Debug.WriteLine("Attenzione impossibile firmare il file :" + exc);
                return null;
            }
        }
Loading...