示例#1
0
 private void addSignature(Stream inputPdfStream, Stream outputPdfStream, PfxData pfxData)
 {
     using (var stamper = PdfStamper.CreateSignature(new CustomPdfReader(inputPdfStream, pfxData.X509PrivateKeys[0], pfxData.PublicKey), outputPdfStream, '\0', null, SignatureData.CertificateFile.AppendSignature))
     {
         tryAddSignature(stamper);
     }
 }
示例#2
0
        public void SignWithThisCert(X509Certificate2 cert, Stream Archivo, string URLDocumento)
        {
            string DestPdfFileName = URLDocumento;


            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, "SHA-1");


            Archivo.Flush(); // Don't know if this is necessary
            Archivo.Position = 0;
            PdfReader              pdfReader           = new PdfReader(Archivo);
            FileStream             signedPdf           = new FileStream(DestPdfFileName, FileMode.Create); //the output pdf file
            PdfStamper             pdfStamper          = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            //here set signatureAppearance at your will
            signatureAppearance.Reason   = ConfigurationManager.AppSettings["firma_RazonInversionista"].ToString();
            signatureAppearance.Location = ConfigurationManager.AppSettings["firma_Ubicacion"].ToString();
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
            //MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES);
            signedPdf.Close();

            //signedPdf = new FileStream(DestPdfFileName, FileMode.Open);
            //return signedPdf;
        }
示例#3
0
        public void Sign(string SigReason, string SigContact, string SigLocation, bool visible)
        {
            PdfReader reader = new PdfReader(this.inputPDF);
            //Activate MultiSignatures
            PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);

            //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
            //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0');

            st.MoreInfo = this.metadata.getMetaData();


            st.XmpMetadata = this.metadata.getStreamedMetaData();
            PdfSignatureAppearance sap = st.SignatureAppearance;

            sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED);
            sap.Reason   = SigReason;
            sap.Contact  = SigContact;
            sap.Location = SigLocation;
            //parametros del itextsharp.text.rectangle: el primero es el punto x infreior, el segundo el punto y inferior,
            //el tercero el punto x superior y el cuarto el punto x superior con lo que tenemos definido la ubicación, el alto y el ancho.
            if (visible)
            {
                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(25, 25, 150, 75), 1, null);
            }

            st.Close();
        }
示例#4
0
        private void sign(X509Certificate2 cert, String imput, String output)
        {
            string SourcePdfFileName = imput;
            string DestPdfFileName   = output;
            string requerente        = "";

            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, "SHA-1");
            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;

            requerente = cert.Subject.Replace("CN=", "").Replace("OU=", "").Replace("DC=", "").Replace("O=", "").Replace("C=", "");

            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(250, 30, 550, 80), 1, "Signature");
            signatureAppearance.Layer2Text = "Assinado de forma digital por " + requerente + Environment.NewLine + "Dados:" + DateTime.Now;

            string pathImage = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "assinatura.png");
            var    image     = iTextSharp.text.Image.GetInstance(pathImage);



            signatureAppearance.SignatureGraphic = image;



            //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;

            //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
        }
示例#5
0
 private void addSignature(Stream inputPdfStream, Stream outputPdfStream, byte[] ownerPassword)
 {
     using (var stamper = PdfStamper.CreateSignature(new PdfReader(inputPdfStream, ownerPassword), outputPdfStream, '\0', null, SignatureData.CertificateFile.AppendSignature))
     {
         tryAddSignature(stamper);
     }
 }
示例#6
0
        private static PdfStamper DoCreateStamperAccordingToEncryptionAndSignature(string sourceFilename,
                                                                                   string destinationFilename, ConversionProfile profile)
        {
            Logger.Debug("Started creating PdfStamper according to Encryption.");

            var        reader     = new PdfReader(sourceFilename);
            var        fileStream = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write);
            PdfStamper stamper    = null;

            var pdfVersion = PdfWriter.VERSION_1_4;

            if (PDFProcessor.DeterminePdfVersion(profile).Equals("1.6"))
            {
                pdfVersion = PdfWriter.VERSION_1_6;
            }

            if (profile.PdfSettings.Signature.Enabled)
            {
                stamper = PdfStamper.CreateSignature(reader, fileStream, pdfVersion);
            }
            else
            {
                stamper = new PdfStamper(reader, fileStream, pdfVersion);
            }

            if (stamper == null)
            {
                throw new ProcessingException("PDFStamper could not be created", 25200);
            }
            return(stamper);
        }
        /// <summary>
        /// PDF imzalar.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="PDFContent"></param>
        /// <returns></returns>
        public byte[] SignPDF(PdfRequestDTO request
                              , byte[] PDFContent
                              )
        {
            //if (PDFContent == null || request == null)
            //{
            //    return null;
            //}
            X509Certificate2   signingCertificate;
            IExternalSignature externalSignature;

            this.SelectSignature(request, out signingCertificate, out externalSignature);
            X509Certificate2[]            chain       = generateCertificateChain(signingCertificate);
            ICollection <X509Certificate> Bouncychain = chainToBouncyCastle(chain);

            ocsp = new OcspClientBouncyCastle();
            crl  = new ITextSharp.iTextSharp.text.pdf.security.CrlClientOnline(Bouncychain);
            PdfReader              pdfReader           = new PdfReader(PDFContent);
            MemoryStream           stream              = new MemoryStream();
            PdfStamper             pdfStamper          = PdfStamper.CreateSignature(pdfReader, stream, '\0', "", true);
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            crlList = new List <ICrlClient>();
            crlList.Add(crl);
            lock (lockSign)
            {
                ITextSharp.iTextSharp.text.pdf.security.MakeSignature.SignDetached(signatureAppearance, externalSignature, Bouncychain, crlList, ocsp, null, 0, CryptoStandard.CMS);
            }
            return(stream.ToArray());
        }
示例#8
0
        public static string TestMultipleSigning(string testFile, ConversionProfile profile, JobPasswords passwords, IPdfProcessor pdfProcessor, Accounts accounts)
        {
            using (var pdfReader = BuildPdfReader(testFile, profile, passwords))
            {
                var doubleSignedFile = testFile.Replace(".pdf", "_doubleSignedFile.pdf");
                var fileStream       = new FileStream(doubleSignedFile, FileMode.Create, FileAccess.Write);
                var tempFile         = testFile.Replace(".pdf", "_tempFile.pdf");

                var intendedPdfVersion = pdfProcessor.DeterminePdfVersion(profile);
                var pdfVersion         = PdfWriter.VERSION_1_4;
                if (intendedPdfVersion == "1.5")
                {
                    pdfVersion = PdfWriter.VERSION_1_5;
                }
                else if (intendedPdfVersion == "1.6")
                {
                    pdfVersion = PdfWriter.VERSION_1_6;
                }
                else if (intendedPdfVersion == "1.7")
                {
                    pdfVersion = PdfWriter.VERSION_1_7;
                }

                //Create Stamper in append mode
                var stamper = PdfStamper.CreateSignature(pdfReader, fileStream, pdfVersion, tempFile, true);

                profile.PdfSettings.Signature.SignaturePage = SignaturePage.LastPage;
                var signer = new ITextSigner();
                signer.SignPdfFile(stamper, profile, passwords, accounts);

                stamper.Close();

                using (var doubleSignedPdfReader = BuildPdfReader(doubleSignedFile, profile, passwords))
                {
                    var af = doubleSignedPdfReader.AcroFields;

                    Assert.AreEqual(2, af.GetSignatureNames().Count, "Number of SignatureNames must be 2" + Environment.NewLine + "(" + testFile + ")");

                    //There is currently no way for testing multisigning.
                    //-> af.SignatureCoversWholeDocument(firstSignatureName) is always false, since a singature can't cover future signing
                    //-> firstSignature.Verify() returns always true.

                    /*
                     * var firstSignatureName = af.GetSignatureNames()[0];
                     * var firstSignature = af.VerifySignature(firstSignatureName);
                     *
                     * if (profile.PdfSettings.Signature.AllowMultiSigning)
                     * {
                     *  Assert.IsTrue(firstSignature.Verify(), "First signature is invalid altough multi signing was enabled");
                     * }
                     * else
                     * {
                     *  Assert.IsFalse(firstSignature.Verify(), "First signature is valid altough multi signing was disabled");
                     * }
                     * //*/

                    return(doubleSignedFile);
                }
            }
        }
示例#9
0
        //Sample from: http://www.rahulsingla.com/blog/2012/09/digitally-sign-and-verify-pdf-documents-in-c-using-itextsharp-5-3-x-library
        // http://stackoverflow.com/questions/14997118/how-do-i-sign-a-pdf-document-using-a-certificate-from-the-windows-cert-store

        /// <summary>
        /// Signs a PDF document using iTextSharp library
        /// </summary>
        /// <param name="certSubjectName">Cerificate subject (prefix) in local certStore.</param>
        /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param>
        /// <param name="destinationPath">The path at which the signed pdf document should be generated</param>
        /// <param name="reason">String describing the reason for signing, would be embedded as part of the signature</param>
        /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param>
        /// <param name="allowInvalidCertificate">Allows also usage of invalid certificate from store.</param>
        public static byte[] SignPdf(string certSubjectName, byte[] sourceDocument, string reason, string location, bool allowInvalidCertificate)
        {
            try
            {
                // reader and stamper
                using (PdfReader reader = new PdfReader(sourceDocument))
                {
                    using (MemoryStream fout = new MemoryStream())
                    {
                        PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');
                        // appearance
                        PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                        appearance.Reason   = reason;
                        appearance.Location = location;
                        // digital signature

                        ICollection <Org.BouncyCastle.X509.X509Certificate> certChain;
                        IExternalSignature es = ResolveExternalSignatureFromCertStore(certSubjectName, allowInvalidCertificate, out certChain);

                        MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CMS);

                        stamper.Close();
                        return(fout.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError("Exception during pdf sign: {0}", ex.Message);
                throw;
            }
        }
示例#10
0
        /// <summary>
        /// Sign
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="output">The output.</param>
        /// <param name="certificate">The certificate.</param>
        public override void Sign(Stream input, Stream output, X509Certificate2 certificate)
        {
            CheckInputOutputAndCertificate(input, output, certificate);
            PdfReader reader = null;

            try
            {
                reader = new PdfReader(input);
                using (var stamper = PdfStamper.CreateSignature(reader, output, '\0', null, true))
                {
                    var cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    var chain = new[] { cp.ReadCertificate(certificate.RawData) };
                    var sig   = stamper.SignatureAppearance;
                    SetSigPosition(sig, reader.AcroFields.GetSignatureNames().Count);
                    SetSigText(sig, chain);
                    SetSigCryptoFromX509(sig, certificate, chain);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
        public void Pkcs11RsaSignatureReuseTest()
        {
            using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(_libraryPath, _tokenSerial, _tokenLabel, _pin, _ckaLabel, _ckaId, _hashAlgorithm))
            {
                byte[]        signingCertificate       = pkcs11RsaSignature.GetSigningCertificate();
                List <byte[]> otherCertificates        = pkcs11RsaSignature.GetAllCertificates();
                ICollection <X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates);

                for (int i = 0; i < 100; i++)
                {
                    string unsignedPdfPath = GetTempDocPath();
                    string signedPdfPath   = GetTempDocPath();

                    try
                    {
                        GenerateRandomPdf(unsignedPdfPath);

                        using (PdfReader pdfReader = new PdfReader(unsignedPdfPath))
                            using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create))
                                using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', GetTempDocPath(), true))
                                    MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES);

                        Assert.IsTrue(1 == VerifySignatureIntegrity(signedPdfPath));
                    }
                    finally
                    {
                        File.Delete(unsignedPdfPath);
                        File.Delete(signedPdfPath);
                    }
                }
            }
        }
示例#12
0
        public Stream SignPDF(Stream pdfstream, Certificate certificate)
        {
            pdfstream.Requires(nameof(pdfstream)).IsNotNull();
            certificate.Requires(nameof(certificate)).IsNotNull();

            var chain      = certificate.Chain;
            var parameters = certificate.Parameters;

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

            using (PdfReader reader = new PdfReader(pdfstream))
            {
                if (reader.IsEncrypted())
                {
                    throw new Exception("[PDFEncryptedException] Target PDF is encrypted or owned, unlock PDF and try again.");
                }
                var outputpdf = new MemoryStream();
                using (PdfStamper st = PdfStamper.CreateSignature(reader, outputpdf, '\0', "tmp.pdf", true))
                {
                    PdfSignatureAppearance appearance = st.SignatureAppearance;

                    appearance.SignDate = DateTime.Now;

                    appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION;

                    MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);

                    var mb = outputpdf.ToArray();
                    return(new MemoryStream(mb));
                }
            }
        }
示例#13
0
        public void Sign(string inputPath, string outPath, string imagePath, bool visible = true)
        {
            X509Store store = new X509Store(StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, X509SelectionFlag.SingleSelection);

            X509Certificate2 cert = sel[0];

            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, "SHA-1");

            PdfReader pdfReader = new PdfReader(inputPath);

            var signedPdf = new FileStream(outPath, FileMode.Create);

            var pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            if (imagePath != null && imagePath != string.Empty)
            {
                signatureAppearance.SignatureGraphic = Image.GetInstance(imagePath);
            }

            signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "Signature");
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;

            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
            Process.Start(outPath);
        }
示例#14
0
        public void Sign(bool visible, string rutaImagen)
        {
            PdfReader reader = new PdfReader(this.inputPDF);
            //Activate MultiSignatures
            PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true);

            //To disable Multi signatures uncomment this line : every new signature will invalidate older ones !
            //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0');

            st.MoreInfo    = this.metadata.getMetaData();
            st.XmpMetadata = this.metadata.getStreamedMetaData();
            PdfSignatureAppearance sap;

            sap = st.SignatureAppearance;
            sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            //string img = "C:\Users\USUARIO\Desktop\darth.png";

            string imagePath = rutaImagen;

            iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(imagePath);

            sap.Reason = "FIRMA ELECTRÓNICA";
            sap.Image  = imagen;

            sap.Location = "PERÚ";
            if (visible)
            {
                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(480, 10, 600, 60), 1, null);
            }
            st.Close();
        }
示例#15
0
        public static bool SignPDF(X509Certificate2 signature, string sourceDocument, string destinationPath)
        {
            if (signature == null)
            {
                return(false);
            }

            PdfReader reader = new PdfReader(sourceDocument);

            using (FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite))
            {
                using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
                {
                    // digital signature
                    var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signature.PrivateKey).Private;
                    IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");

                    Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                    Org.BouncyCastle.X509.X509Certificate[]     chain = new[] { cp.ReadCertificate(signature.RawData) };

                    try
                    {
                        MakeSignature.SignDetached(stamper.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS);
                    }
                    catch (CryptographicException ex)
                    {
                        return(false);
                    }

                    stamper.Close();
                }
            }

            return(true);
        }
示例#16
0
        public static byte[] SignPDFBytes(X509Certificate2 signatureCert, byte[] pdf)
        {
            byte[]       result;
            MemoryStream ms = new MemoryStream();

            PdfReader reader = new PdfReader(pdf);

            using (PdfStamper signer = PdfStamper.CreateSignature(reader, ms, '\0'))
            {
                // digital signature
                var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(signatureCert.PrivateKey).Private;
                IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");

                Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
                Org.BouncyCastle.X509.X509Certificate[]     chain = new[] { cp.ReadCertificate(signatureCert.RawData) };

                try
                {
                    MakeSignature.SignDetached(signer.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS);

                    result = ms.ToArray();
                }
                catch (CryptographicException ex)
                {
                    throw;
                }

                signer.Close();
            }

            return(result);
        }
示例#17
0
        public void sign(X509Certificate2 cert, String filename, String imageName, String output)
        {
            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, "SHA-1");

            PdfReader pdfReader = new PdfReader(filename);

            FileStream signedPdf = new FileStream(output, FileMode.Create);

            PdfStamper             pdfStamper          = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
            Image img = Image.GetInstance(imageName);

            img.Alignment = iTextSharp.text.Image.UNDERLYING;
            signatureAppearance.SignatureGraphic = img;

            signatureAppearance.Acro6Layers = true;
            int x = Convert.ToInt32(xTextBox.Text);
            int y = Convert.ToInt32(yTextBox.Text);
            int w = Convert.ToInt32(widthTextBox.Text);
            int h = Convert.ToInt32(heightTextBox.Text);

            signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, w, h), pdfReader.NumberOfPages, "Signature");
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;

            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
        }
示例#18
0
        public void AddLtv(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient tsa)
        {
            PdfReader       r       = new PdfReader(src);
            FileStream      fos     = new FileStream(dest, FileMode.Create);
            PdfStamper      stp     = PdfStamper.CreateSignature(r, fos, '\0', null, true);
            LtvVerification v       = stp.LtvVerification;
            AcroFields      fields  = stp.AcroFields;
            List <String>   names   = fields.GetSignatureNames();
            String          sigName = names[names.Count - 1];
            PdfPKCS7        pkcs7   = fields.VerifySignature(sigName);

            if (pkcs7.IsTsp)
            {
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            }
            else
            {
                foreach (String name in names)
                {
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                }
            }
            PdfSignatureAppearance sap = stp.SignatureAppearance;

            LtvTimestamp.Timestamp(sap, tsa, null);
        }
示例#19
0
文件: PdfSign.cs 项目: Lietuva2/LT2
        /// <summary>
        /// Signs a PDF document using iTextSharp library
        /// </summary>
        /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param>
        /// <param name="reason">String describing the reason for signing, would be embedded as part of the signature</param>
        /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param>
        public static byte[] SignPdfFile(byte[] sourceDocument, string reason, string location)
        {
            var cert = DigitalSignature.GetStoreCertificate();

            var cp        = new Org.BouncyCastle.X509.X509CertificateParser();
            var pdfCert   = cp.ReadCertificate(cert.RawData);
            var certChain = new[] { pdfCert };

            // reader and stamper
            PdfReader reader = new PdfReader(sourceDocument);

            using (MemoryStream fout = new MemoryStream())
            {
                using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
                {
                    // appearance
                    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                    appearance.Reason   = reason;
                    appearance.Location = location;
                    var rect = reader.GetPageSize(1);
                    appearance.SetVisibleSignature(new Rectangle(rect.Width - 128, rect.Height - 78, rect.Width - 10, rect.Height - 20), 1, null);
                    // digital signature
                    IExternalSignature es = new X509Certificate2Signature(cert, "SHA1");
                    MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CMS);

                    stamper.Close();
                }

                return(fout.ToArray());
            }
        }
示例#20
0
        public void Sign(String keystore, String src, String name, String dest)
        {
            Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
            String      alias = "";
            ICollection <X509Certificate> chain = new List <X509Certificate>();

            // searching for 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;

            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.SetVisibleSignature(name);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
        }
示例#21
0
        public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk,
                         String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
                         String contact, DateTime signDate, String fullName)
        {
            // Creating the reader and the stamper
            PdfReader  reader  = new PdfReader(src);
            FileStream os      = new FileStream(dest, FileMode.Create);
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
            // Creating the appearance
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;

            appearance.Reason   = reason;
            appearance.Location = location;
            appearance.SetVisibleSignature(name);
            appearance.Contact  = contact;
            appearance.SignDate = signDate;
            MySignatureEvent eEvent = new MySignatureEvent();

            eEvent.FullName           = fullName;
            appearance.SignatureEvent = eEvent;
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);

            MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
        }
示例#22
0
        public byte[] Sign(byte[] pdf, SignInformation signInfo)
        {
            PdfReader    document = new PdfReader(pdf);
            MemoryStream stream   = new MemoryStream();

            PdfStamper pdfStamper = PdfStamper.CreateSignature(document, stream, '\0');

            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            signatureAppearance.Reason                 = signInfo.reason;                                  //Reason
            signatureAppearance.Location               = signInfo.location;                                //Location
            signatureAppearance.CertificationLevel     = signInfo.certifyLevel;
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Rendering mode

            IExternalSignature signature = new RSAProviderPrivateKey(signInfo.cert, signInfo.hashAlgorithm);

            try
            {
                //Do signing
                MakeSignature.SignDetached(signatureAppearance, signature, signInfo.chain, null, null, null, 0, signInfo.sigType);
            }
            catch (Exception e)
            {
                throw new Exception("Cannot sign the PDF file.", e);
            }

            return(stream.ToArray());
        }
示例#23
0
 public PDFSigner(PdfReader Reader, string UserName)
 {
     reader     = Reader;
     ms         = new MemoryStream();
     stamper    = PdfStamper.CreateSignature(reader, ms, '\0');
     appearance = stamper.SignatureAppearance;
     userName   = UserName;
 }
示例#24
0
文件: Sign_.cs 项目: Ruke45/DCNCENew
        public bool signCertificate(string DocumentPath, string CertificateSavePath, Stream privateKeyStream, string keyPassword)
        {
            try
            {
                Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());

                privateKeyStream.Dispose();

                //then Iterate throught certificate entries to find the private key entry
                string alias = null;
                foreach (string tAlias in pk12.Aliases)
                {
                    if (pk12.IsKeyEntry(tAlias))
                    {
                        alias = tAlias;
                        break;
                    }
                }
                var pk = pk12.GetKey(alias).Key;

                // reader and stamper
                PdfReader reader    = new PdfReader(DocumentPath);
                int       PageCount = reader.NumberOfPages;

                using (FileStream fout = new FileStream(CertificateSavePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true))
                    {
                        // appearance
                        PdfSignatureAppearance appearance = stamper.SignatureAppearance;
                        //appearance.Image = new iTextSharp.text.pdf.PdfImage();
                        //appearance.Reason = reason;
                        //   appearance.Location = location;
                        appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(220, 165, 420, 250), PageCount, "Icsi-Vendor");//.IsInvisible();//s
                        //220,165, 435, 310
                        //lly - gose up  llx - is width 210,245,495,620  500, 300, 297, 200
                        //iTextSharp.text.Image watermark = iTextSharp.text.Image.GetInstance(SignatureIMGPath);
                        //appearance.Image = watermark;
                        //appearance.Image.ScaleToFit(70, 70);
                        ////appearance.Image.Alignment=100;
                        //appearance.Image.SetAbsolutePosition(100, 100);
                        //appearance.GetAppearance().AddImage(watermark);

                        //digital signature
                        IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
                        MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

                        stamper.Close();
                    }
                }
                return(true);
            }
            catch (Exception Ex)
            {
                ErrorLog.LogError(Ex);
                return(false);
            }
        }
示例#25
0
        public async Task DigitallySign(int idDocument, string userId, string password, byte[] certificateData, string reason, string location)
        {
            var document = await dbContext
                           .Documents
                           .FirstAsync(it => it.IdDocument == idDocument);

            var lastState = await dbContext.DocumentStates.Include(it => it.DocumentData).Where(it => it.IdDocument == idDocument).LastAsync();

            var unsignedData = ((DocumentDataUpload)lastState.DocumentData).Data;

            var store = new Pkcs12Store(new MemoryStream(certificateData), password.ToCharArray());
            var alias = string.Empty;

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

            var pk    = store.GetKey(alias);
            var chain = new List <X509Certificate>();

            foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
            {
                chain.Add(c.Certificate);
            }

            var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate(certificateData, password);

            var signedPdfData = new MemoryStream();

            using (var reader = new PdfReader(unsignedData))
            {
                var stp = PdfStamper.CreateSignature(reader, signedPdfData, '\0');
                stp.SignatureAppearance.Reason   = reason;
                stp.SignatureAppearance.Location = location;
                stp.SignatureAppearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, null);
                var es = new PrivateKeySignature(pk.Key as RsaPrivateCrtKeyParameters, DigestAlgorithms.SHA256);
                MakeSignature.SignDetached(stp.SignatureAppearance, es, chain, null, null, null, 0, CryptoStandard.CMS);

                stp.Close();
            }

            dbContext.Entry(lastState).State = EntityState.Detached;
            lastState.IdDocumentState        = 0;
            lastState.IdDocumentData         = 0;
            lastState.StatusDate             = DateTime.Now;
            lastState.IsDigitallySigned      = true;
            lastState.Version      = GetNextVersion(lastState.Version, lastState.DocumentStatus);
            lastState.DocumentData = new DocumentDataUpload {
                Data = signedPdfData.ToArray()
            };

            dbContext.DocumentStates.Add(lastState);
        }
示例#26
0
        public static bool SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA)
        {
            PdfReader  objReader  = null;
            PdfStamper objStamper = null;

            try
            {
                X509CertificateParser objCP    = new Org.BouncyCastle.X509.X509CertificateParser();
                X509Certificate[]     objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

                IList <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(new CrlClientOnline(objChain));

                objReader  = new PdfReader(Source);
                objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);

                // Creamos la apariencia
                PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance;
                signatureAppearance.Reason = "Inforegistro, S.L.";
                //signatureAppearance.Location = Location;

                // Custom signature appearance text
                var font = FontFactory.GetFont("Times New Roman", 11, iTextSharp.text.Font.BOLDITALIC, BaseColor.DARK_GRAY);
                signatureAppearance.Layer2Font = font;
                signatureAppearance.Layer2Text = "Firmado digitalmente por \r\nInforegistro, S.L.\r\nFecha  " + DateTime.Now.ToShortDateString();
                var rectangle = new Rectangle(350, 30, 500, 120);

                // Si está la firma visible:
                if (AddVisibleSign)
                {
                    signatureAppearance.SetVisibleSignature(rectangle, 2, "Inforegistro");
                }

                ITSAClient  tsaClient  = null;
                IOcspClient ocspClient = null;

                // Creating the signature
                IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1");
                MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
                return(File.Exists(Target));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (objReader != null)
                {
                    objReader.Close();
                }
                if (objStamper != null)
                {
                    objStamper.Close();
                }
            }
        }
示例#27
0
        public string Execute(SingInfo singInfo)
        {
            var certificate = this.certificadoA3.Obter();

            this.cadeiaTempo = this.certificadoA3.CadeiaCertificadoTempo();

            this.MontarEstruturaCertificacao(certificate);

            var pdfAux = Path.Combine(
                Path.GetDirectoryName(singInfo.SourcePdf),
                Path.GetFileNameWithoutExtension(singInfo.SourcePdf) + "-aux.pdf");

            using (var reader = new PdfReader(singInfo.SourcePdf))
            {
                using (var os = new FileStream(pdfAux, FileMode.Create))
                {
                    var stamper = PdfAStamper.CreateSignature(reader, os, '\0', PdfAConformanceLevel.PDF_A_2A);

                    var appearance = stamper.SignatureAppearance;

                    var caminhoFonte2 = @"C:\Windows\Fonts\cour.ttf";
                    appearance.Layer2Font = FontFactory.GetFont(caminhoFonte2, BaseFont.WINANSI, BaseFont.EMBEDDED, 8);
                    appearance.Reason     = singInfo.SignatureReason;
                    appearance.Contact    = singInfo.SignatureContact;
                    appearance.Location   = singInfo.SignatureLocation;

                    appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;

                    var pks = new X509Certificate2Signature(certificate, DigestAlgorithms.SHA256);

                    MakeSignature.SignDetached(
                        appearance,
                        pks,
                        this.chain,
                        this.crlList,
                        this.ocspClient,
                        this.tsaClient,
                        EstimatedSize,
                        CryptoStandard.CMS);
                }
            }

            using (var reader = new PdfReader(pdfAux))
            {
                using (var os = new FileStream(singInfo.TargetPdf, FileMode.Create))
                {
                    var stamper    = PdfStamper.CreateSignature(reader, os, '\0', null, true);
                    var appearance = stamper.SignatureAppearance;

                    this.AdicionarLtv(stamper, appearance);
                }
            }

            this.RemoverArquivoTemporario(pdfAux);

            return(singInfo.TargetPdf);
        }
示例#28
0
        void Button4Click(object sender, EventArgs e)
        {
            if (!tsaCbx.Checked || TSAUrlTextBox.Text == "")
            {
                MessageBox.Show("Marca temporale non selezionata, oppure server non definito");
                return;
            }

            string TSA_URL   = TSAUrlTextBox.Text;
            string TSA_ACCNT = tsaLogin.Text;
            string TSA_PASSW = tsaPwd.Text;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string   foldername = fbd.SelectedPath;
                string[] files      = Directory.GetFiles(foldername, "*.pdf");
                pb.Minimum = 0;
                pb.Maximum = files.Length;
                pb.Visible = true;
                lb2.Items.Clear();
                foreach (string s in files)
                {
                    //just filename
                    try {
                        string ext = s.Substring(1 + s.LastIndexOf(@".")).ToLowerInvariant();
                        if (ext == "pdf" || ext == "PDF")
                        {
                            //ricreo il percorso con il nome del nuovo file
                            string          file      = s.Substring(1 + s.LastIndexOf(@"\"));
                            string          NuovoFile = s.Substring(0, s.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_validato_" + DateTime.Now.ToFileTime() + ".pdf";
                            PdfReader       r         = new PdfReader(s);
                            FileStream      fout      = new FileStream(NuovoFile, FileMode.Create);
                            PdfStamper      stp       = PdfStamper.CreateSignature(r, fout, '\0', null, true);
                            LtvVerification v         = stp.LtvVerification;
                            AcroFields      af        = stp.AcroFields;
                            foreach (string sigName in af.GetSignatureNames())
                            {
                                v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientImp(), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                            }
                            PdfSignatureAppearance sap = stp.SignatureAppearance;
                            TSAClientBouncyCastle  tsa = new TSAClientBouncyCastle(TSA_URL, TSA_ACCNT, TSA_PASSW, 6500, "sha256");
                            LtvTimestamp.Timestamp(sap, tsa, null);
                            lb2.Items.Add(NuovoFile);
                            lb2.Refresh();
                            pb.Increment(1);
                        }
                    }
                    catch (Exception ex) {
                        MessageBox.Show(ex.ToString());
                        pb.Visible = false;
                        return;
                    }
                }
                MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata");
                pb.Visible = false;
            }
        }
        void CreateITextAppearance(byte[] Content)
        {
            var content = Content;
            var reader  = new PdfReader(content);

            ms = new MemoryStream();
            var stamper = PdfStamper.CreateSignature(reader, ms, '\0');

            appearance = stamper.SignatureAppearance;
        }
示例#30
0
        public byte[] SignWithLTVEnable(byte[] pdf, SignInformation signInfo)
        {
            PdfReader    document = new PdfReader(pdf);
            MemoryStream stream   = new MemoryStream();

            //PdfStamper pdfStamper = new PdfStamper(document, stream, '0');
            PdfStamper pdfStamper = PdfStamper.CreateSignature(document, stream, '\0');

            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

            signatureAppearance.Reason                 = signInfo.reason;                                  //Reason
            signatureAppearance.Location               = signInfo.location;                                //Location
            signatureAppearance.CertificationLevel     = signInfo.certifyLevel;
            signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Rendering mode

            IExternalSignature signature = new RSAProviderPrivateKey(signInfo.cert, signInfo.hashAlgorithm);
            bool isTsaConnected          = false;

            for (int retry = 0; retry < 5; retry++)
            {
                try
                {
                    //int hash = tsaClient.GetHashCode();
                    string testString = "test";
                    byte[] digest;
                    using (System.Security.Cryptography.SHA256Managed sha256 = new System.Security.Cryptography.SHA256Managed())
                    {
                        digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(testString));
                    }
                    signInfo.tsaClient.GetTimeStampToken(digest);
                    isTsaConnected = true;
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                Console.WriteLine("retry " + (retry + 1));
            }
            if (signInfo.tsaClient != null && signInfo.crlList != null && isTsaConnected)
            {
                try
                {
                    //Do signing
                    MakeSignature.SignDetached(signatureAppearance, signature, signInfo.chain, signInfo.crlList, null, signInfo.tsaClient, 0, signInfo.sigType);
                }
                catch (Exception e)
                {
                    throw new Exception("Cannot sign the PDF file.", e);
                }
            }

            return(stream.ToArray());
        }