コード例 #1
0
        private void ProcessBtn_Click(object sender, EventArgs e)
        {
            debug("*****Started (document = " + inputBox.Text + " => " + outputBox.Text + ") ");

            debug("Checking certificate ...");
            Cert myCert = null;

            try
            {
                string tsaUrl = String.IsNullOrEmpty(TSAUrlTextBox.Text) ? null : TSAUrlTextBox.Text;
                if (certificateData != null)
                {
                    //X509Certificate2 cert = certsListBox.SelectedItem as X509Certificate2;
                    byte[] bytes = certificateData.Export(X509ContentType.Pfx, certificatePwdBox.Text);
                    myCert = new Cert(bytes, certificatePwdBox.Text, tsaUrl, tsaLogin.Text, tsaPwd.Text);
                }
                else
                {
                    myCert = new Cert(certificateTextBox.Text, certificatePwdBox.Text, tsaUrl, tsaLogin.Text, tsaPwd.Text);
                }

                debug("Certificate OK");
            }
            catch (Exception ex)
            {
                debug("Warning : No valid certificate found, please make sure you entered a valid certificate file and password");
                //debug("Exception : " + ex.ToString());
                debug(" ==> Continue ... the document will not be signed !");
                //return;
            }

            debug("Checking encryption options ...");
            PDFEnc.UserPwd  = encUserPwd.Text;
            PDFEnc.OwnerPwd = encOwnerPwd.Text;


            debug("Creating new MetaData object... ");

            //Adding Meta Datas
            MetaData MyMD = new MetaData();

            MyMD.Author   = authorBox.Text;
            MyMD.Title    = titleBox.Text;
            MyMD.Subject  = subjectBox.Text;
            MyMD.Keywords = kwBox.Text;
            MyMD.Creator  = creatorBox.Text;
            MyMD.Producer = prodBox.Text;


            debug("Processing document ... ");
            PDFSigner      pdfs  = new PDFSigner(inputBox.Text, outputBox.Text, myCert, MyMD);
            PDFSignatureAP sigAp = new PDFSignatureAP();

            sigAp.SigReason   = Reasontext.Text;
            sigAp.SigContact  = Contacttext.Text;
            sigAp.SigLocation = Locationtext.Text;
            sigAp.Visible     = SigVisible.Checked;
            sigAp.Multi       = multiSigChkBx.Checked;
            sigAp.Page        = Convert.ToInt32(numberOfPagesUpDown.Value);
            sigAp.CustomText  = custSigText.Text;

            if (sigImgBox.Image != null)
            {
                MemoryStream ms = new MemoryStream();
                sigImgBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                sigAp.RawData = ms.ToArray();
                ms.Close();
            }

            sigAp.SigX = (float)sigPosX.Value;
            sigAp.SigY = (float)sigPosY.Value;
            sigAp.SigW = (float)sigWidth.Value;
            sigAp.SigH = (float)sigHeight.Value;

            pdfs.Sign(sigAp, encryptChkBx.Checked, PDFEnc);

            debug("Done :)");

            MessageBox.Show("The document has been succesfully processed", "iSafePDF :: Signature done", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
コード例 #2
0
ファイル: PDFSigner.cs プロジェクト: jovisudiardi/iSafePDF
        public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption Enc)
        {
            PdfReader reader = new PdfReader(this.inputPDF);

            FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write);


            PdfStamper st;

            if (this.myCert == null) //No signature just write meta-data and quit
            {
                st = new PdfStamper(reader, fs);
            }
            else
            {
                st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi);
            }

            if (encrypt && Enc != null)
            {
                Enc.Encrypt(st);
            }
            //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY);

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

            if (this.myCert == null) //No signature just write meta-data and quit
            {
                st.Close();
                return;
            }

            PdfSignatureAppearance sap = st.SignatureAppearance;

            //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED);

            sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED);

            sap.Reason   = sigAP.SigReason;
            sap.Contact  = sigAP.SigContact;
            sap.Location = sigAP.SigLocation;
            if (sigAP.Visible)
            {
                iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page);
                sap.Image      = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData);
                sap.Layer2Text = sigAP.CustomText;

                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null);
            }



            /////
            PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

            dic.Reason           = sap.Reason;
            dic.Location         = sap.Location;
            dic.Contact          = sap.Contact;
            dic.Date             = new PdfDate(sap.SignDate);
            sap.CryptoDictionary = dic;

            int contentEstimated = 15000;
            // Preallocate excluded byte-range for the signature content (hex encoded)
            Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            sap.PreClose(exc);

            PdfPKCS7 sgn           = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA1", false);
            IDigest  messageDigest = DigestUtilities.GetDigest("SHA1");
            Stream   data          = sap.RangeStream;

            byte[] buf = new byte[8192];
            int    n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            byte[] hash = new byte[messageDigest.GetDigestSize()];
            messageDigest.DoFinal(hash, 0);
            DateTime cal = DateTime.Now;

            byte[] ocsp = null;
            if (this.myCert.Chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]);
                if (url != null && url.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle(this.myCert.Chain[0], this.myCert.Chain[1], url).GetEncoded();
                }
            }
            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);


            byte[] paddedSig = new byte[contentEstimated];


            if (this.myCert.Tsc != null)
            {
                byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp);
                System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new Exception("Not enough space for signature");
                }
            }



            PdfDictionary dic2 = new PdfDictionary();

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

            //////
            //st.Close();
        }