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(); }
/// <summary> /// Sign (fill) named field in the document soft way (using existing stamper) /// </summary> /// <param name="stamper">PdfStamper</param> /// <param name="fieldName">Field to be signed</param> /// <param name="reason">Sign reason</param> /// <param name="location">Sign location</param> /// <param name="graphics">Sign graphic</param> /// <param name="certFile">PFX certificate</param> /// <param name="certPassword">password of certificate</param> /// <param name="renderingMode">SignatureRender renderingMode</param> /// <param name="certificationLevel">PdfSignatureAppearance Certification Level</param> /// <returns>Successfull or not</returns> public static bool SignField(ref PdfStamper stamper, string fieldName, string reason, string location, Bitmap graphics, string certFile, string certPassword, PdfSignatureAppearance.SignatureRender renderingMode = PdfSignatureAppearance.SignatureRender.GraphicAndDescription, int certificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { bool result = false; try { if (stamper.Reader.AcroFields.Fields.ContainsKey(fieldName)) { PdfSignatureAppearance psa = GetPSA(fieldName, stamper, graphics, reason, location, renderingMode, certificationLevel); Pkcs12Store store = new Pkcs12Store(new FileStream(certFile, FileMode.Open), certPassword.ToCharArray()); string alias = ""; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry ake = store.GetKey(alias); foreach (X509CertificateEntry c in store.GetCertificateChain(alias)) { chain.Add(c.Certificate); } RsaPrivateCrtKeyParameters parameters = ake.Key as RsaPrivateCrtKeyParameters; psa.SetCrypto(parameters, chain.ToArray(), null, PdfSignatureAppearance.WINCER_SIGNED); result = true; } else { result = false; } } catch (Exception e) { Console.WriteLine(e.Message); result = false; } return(result); }
public void SignDocument() { //if( !IsLoaded ) { return; } //TODO: PdfDocumentWrapper.SignDocument(): consider throwing an exception on null. PdfReader reader = new PdfReader(new byte[0]); Document document = new Document(reader.GetPageSizeWithRotation(1)); using (MemoryStream stream = new MemoryStream()) { PdfStamper stp = PdfStamper.CreateSignature(reader, stream, PdfWriter.VERSION_1_7); PdfSignatureAppearance sap = stp.SignatureAppearance; sap.SetVisibleSignature("blah"); sap.SignDate = DateTime.Now; sap.SetCrypto(null, null, null, null); sap.Reason = ""; sap.Location = ""; sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; PdfSignature sig = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); sig.Date = new PdfDate(sap.SignDate); //sig.Name = PdfPKCS7.GetSubjectFields( sig.Reason = sap.Reason; sig.Location = sap.Location; sap.CryptoDictionary = sig; Dictionary <PdfName, int> dic = new Dictionary <PdfName, int>(); dic[PdfName.CONTENTS] = 4000 * 2 + 2; sap.PreClose(dic); //PdfCopy writer = new PdfCopy( document, stream ); //document.Open(); //for( int i = 0; i < reader.NumberOfPages; ) //{ // writer.AddPage( writer.GetImportedPage( reader, ++i ) ); //} //PRAcroForm form = reader.AcroForm; //if( form != null ) { writer.CopyAcroForm( reader ); } stp.Close(); document.Close(); reader.Close(); //_pdf = stream.ToArray(); } }
private static void SetSigCryptoFromX509(PdfSignatureAppearance sigAppearance, X509Certificate2 card, X509Certificate[] chain) { sigAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.WINCER_SIGNED); var dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1) { Date = new PdfDate(sigAppearance.SignDate), Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"), Reason = sigAppearance.Reason, Location = sigAppearance.Location }; sigAppearance.CryptoDictionary = dic; const int csize = 4000; var exc = new Dictionary <PdfName, int> { { PdfName.CONTENTS, csize * 2 + 2 } }; sigAppearance.PreClose(exc); HashAlgorithm sha = new SHA1CryptoServiceProvider(); var s = sigAppearance.RangeStream; int read; var buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { sha.TransformBlock(buff, 0, read, buff, 0); } sha.TransformFinalBlock(buff, 0, 0); var pk = SignMsg(sha.Hash, card, false); var outc = new byte[csize]; var dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sigAppearance.Close(dic2); }
public static void signPdfFile(string sourceDocument, string destinationPath, Stream privateKeyStream, string keyPassword, string reason, string location) { 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; var ce = pk12.GetCertificateChain(alias); var chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } // reader and stamper PdfReader reader = new PdfReader(sourceDocument); FileStream fout = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite); PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SetCrypto(pk, chain, null, PdfSignatureAppearance.SELF_SIGNED); appearance.Reason = reason; appearance.Location = location; stamper.Close(); }
/*public void Verify(string pdfFile, Stream fileStream) * { * * //KeyStore kall = PdfPKCS7.loadCacertsKeyStore(); * var parser = new X509CertificateParser(fileStream); * var certifi = parser.ReadCertificate (); * fileStream.Dispose(); * * string pathToFiles = HttpContext.Current.Server.MapPath("~/UploadFile/output/ForCekTandaTangan.pdf"); * PdfReader reader = new PdfReader(pathToFiles); * AcroFields af = reader.AcroFields; * var names = af.GetSignatureNames(); * if (names.Count == 0) * { * System.Diagnostics.Debug.WriteLine("Tidak ada ttdnya"); * } * else * { * System.Diagnostics.Debug.WriteLine("IKI lo TTD ne yooow"); * } * foreach (string name in names) * { * if (!af.SignatureCoversWholeDocument(name)) * { * System.Diagnostics.Debug.WriteLine("The signature: {0} does not covers the whole document.", name); * } * System.Diagnostics.Debug.WriteLine("Signature Name: " + name); * System.Diagnostics.Debug.WriteLine("Signature covers whole document: " + af.SignatureCoversWholeDocument(name)); * System.Diagnostics.Debug.WriteLine("Document revision: " + af.GetRevision(name)); * * PdfPKCS7 pk = af.VerifySignature(name); * var cal = pk.SignDate; * var pkc = pk.Certificates; * // TimeStampToken ts = pk.TimeStampToken; * if (!pk.Verify()) * { * System.Diagnostics.Debug.WriteLine("The signature could not be verified"); * } else * { * System.Diagnostics.Debug.WriteLine("Name signature: " + pk.SignName); * System.Diagnostics.Debug.WriteLine("Reason signature: " + pk.Reason); * System.Diagnostics.Debug.WriteLine("Location signature: " + pk.Location); * System.Diagnostics.Debug.WriteLine("Date signature: " + pk.SignDate); * System.Diagnostics.Debug.WriteLine("Version signature: " + pk.SigningInfoVersion); * System.Diagnostics.Debug.WriteLine("Sertificate signature: " + pk.SigningCertificate); * } * * //IList<VerificationException>[] fails = PdfPKCS7.VerifyCertificates(pkc, new X509Certificate[] { certifi }, null, cal); * //Object[] fails = PdfPKCS7.VerifyCertificates(pkc, new X509Certificate[] { }, null, cal); * //if (fails != null) * //{ * // System.Diagnostics.Debug.WriteLine("The file is not signed using the specified key-pair."); * //} * } * }*/ //To disable Multi signatures uncomment this line : every new signature will invalidate older ones ! line 251 //PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0'); public void Sign(string SigReason, string SigContact, string SigLocation, string pic, bool visible, int posX, int posY) { //Activate MultiSignatures PdfReader reader = new PdfReader(this.inputPDF); PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true); //iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(pic); Image sigImg = Image.GetInstance(pic); // MAX_WIDTH, MAX_HEIGHT sigImg.ScaleToFit(150, 50); // Set signature position on page sigImg.SetAbsolutePosition(posX, 840 - posY); // Add signatures to desired page PdfContentByte over = st.GetOverContent(1); over.AddImage(sigImg); st.MoreInfo = this.metadata.getMetaData(); st.XmpMetadata = this.metadata.getStreamedMetaData(); PdfSignatureAppearance sap = st.SignatureAppearance; sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.Reason = SigReason; sap.Contact = SigContact; sap.Location = SigLocation; if (visible) { sap.SetVisibleSignature( new Rectangle(posX, 840 - posY, posX + 150, (840 - posY) + 50), 1, null); } st.Close(); }
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.WINCER_SIGNED); sap.Reason = SigReason; sap.Contact = SigContact; sap.Location = SigLocation; if (visible) { sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null); } st.Close(); }
private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords) { Signature signing = profile.PdfSettings.Signature; if (!signing.Enabled) //Leave without signing { return; } Logger.Debug("Start signing file."); signing.CertificateFile = Path.GetFullPath(signing.CertificateFile); if (string.IsNullOrEmpty(jobPasswords.PdfSignaturePassword)) { Logger.Error("Launched signing without certification password."); throw new ProcessingException("Launched signing without certification password.", 12204); } if (IsValidCertificatePassword(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong."); throw new ProcessingException("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.", 12200); } if (CertificateHasPrivateKey(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key."); throw new ProcessingException( "Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.", 12201); } var fsCert = new FileStream(signing.CertificateFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, jobPasswords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; X509CertificateEntry[] x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (int k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim())) { if (!signing.TimeServerIsSecured) { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl); } else { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName, signing.TimeServerPassword); } } PdfSignatureAppearance psa = stamper.SignatureAppearance; if (tsc == null) { psa.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { psa.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } if (!profile.PdfSettings.Signature.AllowMultiSigning) { //Lock PDF, except for annotations and form filling (irrelevant for PDFCreator) psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS; } psa.Reason = signing.SignReason; psa.Contact = signing.SignContact; psa.Location = signing.SignLocation; if (signing.DisplaySignatureInDocument) { int signPage = SignPageNr(stamper, signing); psa.SetVisibleSignature(new Rectangle(signing.LeftX, signing.LeftY, signing.RightX, signing.RightY), signPage, null); } var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = psa.Reason; dic.Location = psa.Location; dic.Contact = psa.Contact; dic.Date = new PdfDate(psa.SignDate); psa.CryptoDictionary = dic; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; psa.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = psa.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } DateTime cal = psa.SignDate; byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = null; try { encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); } catch (Exception ex) { throw new ProcessingException( ex.GetType() + " while connecting to timeserver (can't connect to timeserver): " + ex.Message, 12205); } if (contentEstimated + 2 < encodedSigTsa.Length) { throw new ProcessingException( "Not enough space for signature", 12202); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new ProcessingException("Not enough space for signature", 12203); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); psa.Close(dic2); }
public void SignDetached() { if (lb.Items.Count > 0) { try { X509Certificate2 card = GetCertificate(); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) }; pb.Minimum = 0; pb.Maximum = lb.Items.Count; pb.Visible = true; foreach (object oFile in lb.Items) { string filePDF = oFile.ToString(); PdfReader reader = new PdfReader(filePDF); int Pagina = 1; int posX = 0, posY = 0, Altezza = 0, Larghezza = 0; //ricreo il percorso con il nome del nuovo file string file = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")); string NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf"; PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked); PdfSignatureAppearance sap = stp.SignatureAppearance; string nPagine = reader.NumberOfPages.ToString(); sap.Reason = cbRagione.Text + nPagine; sap.Contact = tbContatto.Text; sap.Location = tbLuogo.Text; if (cbFirmaVisibile.Checked == true) //firma visibile { if (rbNuovaPagina.Checked) //firma su nuova pagina { Pagina = reader.NumberOfPages + 1; stp.InsertPage(Pagina, reader.GetPageSize(1)); iTextSharp.text.Rectangle rect = reader.GetPageSize(Pagina); int w = Convert.ToInt32(rect.Width); int h = Convert.ToInt32(rect.Height); posX = 20; posY = h - 120; Larghezza = posX + 100; Altezza = posY + 100; } else if (rbVecchiaPagina.Checked) //firma su pagina esistente { int IndiceScelto = lbPosizioneFirma.SelectedIndex; int paginaScelta = (IndiceScelto <= 3) ? 1 : reader.NumberOfPages; iTextSharp.text.Rectangle rect = reader.GetPageSize(paginaScelta); int w = Convert.ToInt32(rect.Width); int h = Convert.ToInt32(rect.Height); Pagina = paginaScelta; /* istruzioni: * 0 Prima Pagina in Alto a Sinistra * 1 Prima Pagina in Alto a Destra * 2 Prima Pagina in Basso a Sinistra * 3 Prima Pagina in Basso a Destra * 4 Ultima Pagina in Alto a Sinistra * 5 Ultima Pagina in Alto a Destra * 6 Ultima Pagina in Basso a Sinistra * 7 Ultima Pagina in Basso a Destra */ switch (IndiceScelto) { case 0: default: case 4: posX = 20; posY = h - 110; Larghezza = posX + 100; Altezza = posY + 100; break; case 1: case 5: posX = w - 110; posY = h - 110; Larghezza = posX + 100; Altezza = posY + 100; break; case 2: case 6: posX = 20; posY = 20; Larghezza = posX + 350; Altezza = posY + 70; break; case 3: case 7: posX = w - 110; posY = 20; Larghezza = posX + 100; Altezza = posY + 100; break; } } sap.SetVisibleSignature(new iTextSharp.text.Rectangle(posX, posY, Larghezza, Altezza), Pagina, null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.Description; //.NameAndDescription; PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.Date = new PdfDate(sap.SignDate); dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); sap.Layer2Text = "Firmato Digitalmente da: " + PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); sap.Layer2Text += "\r\nData: " + sap.SignDate; sap.Layer2Text += "\r\nRagione: " + sap.Reason; if (sap.Reason != null) { dic.Reason = sap.Reason; } if (sap.Location != null) { dic.Location = sap.Location; } if (sap.Contact != null) { dic.Contact = sap.Contact; } sap.CryptoDictionary = dic; int contentEstimated = 56000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream s = sap.GetRangeStream(); MemoryStream ss = new MemoryStream(); int read = 0; byte[] buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { ss.Write(buff, 0, read); } byte[] pk; if (tsaCbx.Checked) //ss.ToArray() { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } else { pk = SignMsg(ss.ToArray(), card, true, false, "", "", ""); } byte[] outc = new byte[contentEstimated]; PdfDictionary dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sap.Close(dic2); //avanzo di 1 la progress bar pb.Increment(1); } MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata"); pb.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Messaggio dal Sistema Windows"); pb.Visible = false; } } }
/// <summary> /// Configura la informacion del certificado digital /// </summary> /// <param name="origen"></param> /// <param name="destino"></param> /// <param name="rutaCertificado"></param> /// <param name="pass"></param> public bool infoCertificado(string origen, string destino, string rutaCertificado, string pass) { bool resultado = false; try { //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("origen " + origen); //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("destino " + destino); //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("rutaCertificado " + rutaCertificado); //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("clave " + pass); //Se obtiene el certficado x509.X509Certificate2 certificado = new x509.X509Certificate2(rutaCertificado, pass); X509CertificateParser objCP = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificado.RawData) }; //Objeto de tipo documento pdf PdfReader objReader = new PdfReader(origen); //Crea el objeto para la firma digital PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(destino, FileMode.Create), '\0'); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; //Configuracion de informacion para la firma digital objSA.SignDate = DateTime.Now; objSA.SetCrypto(null, objChain, null, null); objSA.Reason = "Comprobante Generado"; objSA.Location = "Uruguay"; objSA.Acro6Layers = true; objSA.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); objSignature.Date = new PdfDate(objSA.SignDate); objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN"); if (objSA.Reason != null) { objSignature.Reason = objSA.Reason; } if (objSA.Location != null) { objSignature.Location = objSA.Location; } objSA.CryptoDictionary = objSignature; int intCSize = 4000; Hashtable objTable = new Hashtable(); objTable[PdfName.CONTENTS] = intCSize * 2 + 2; objSA.PreClose(objTable); Stream objStream = objSA.RangeStream; HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider(); int intRead = 0; byte[] bytBuffer = new byte[8192]; while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0) { objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0); } objSHA1.TransformFinalBlock(bytBuffer, 0, 0); byte[] bytPK = firmarDocumento(objSHA1.Hash, certificado); byte[] bytOut = new byte[intCSize]; PdfDictionary objDict = new PdfDictionary(); Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length); objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true)); objStream.Close(); objSA.Close(objDict); resultado = true; } catch (Exception ex) { SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("ERROR: " + ex.ToString()); } return(resultado); }
public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption enc) { byte[] ownerPassword = null; if (!string.IsNullOrEmpty(enc.OwnerPwd)) { ownerPassword = DocWriter.GetISOBytes(enc.OwnerPwd); } PdfReader reader = new PdfReader(this.inputPDF, ownerPassword); 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); } // Remove yellow question mark (green check mark is still used though) //sap.GetLayer(1); // The first signature is a certification //if (!sigAP.Multi) //{ // //sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; // sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING; //} 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, "SHA-256", false); IDigest messageDigest = DigestUtilities.GetDigest("SHA-256"); // change for itextsharp-all-5.2.1 Stream data = sap.GetRangeStream(); 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(); // change for itextsharp-all-5.2.1 ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url); } } 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)); //// Lock all fields after signing (backport from iText 5.4.4) - wrong - doesn't work //PdfDictionary lockDic = new PdfDictionary(new PdfName("SigFieldLock")); //lockDic.Put(PdfName.ACTION, new PdfName("All")); //lockDic.Put(PdfName.P, new PdfNumber(1)); //dic2.Put(PdfName.LOCK, lockDic); sap.Close(dic2); //st.Close(); }
private MemoryStream Assinar2(MemoryStream ArquivoOrigem, X509Certificate2 cert, ref byte[] pkcs7) { this.card = cert; X509CertificateParser x509CertificateParser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] array = new Org.BouncyCastle.X509.X509Certificate[] { x509CertificateParser.ReadCertificate(this.card.RawData) }; PdfReader reader = new PdfReader(ArquivoOrigem); MemoryStream memoryStream = new MemoryStream(); PdfStamper pdfStamper = PdfStamper.CreateSignature(reader, memoryStream, '\0', null, true); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SetCrypto(null, array, null, PdfSignatureAppearance.SELF_SIGNED); signatureAppearance.Reason = this.proposito; signatureAppearance.Contact = this.contato; signatureAppearance.Location = this.localizacao; signatureAppearance.CryptoDictionary = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")) { Reason = signatureAppearance.Reason, Location = signatureAppearance.Location, Contact = signatureAppearance.Contact, Date = new PdfDate(signatureAppearance.SignDate) }; int num = 15000; Dictionary <PdfName, int> dictionary = new Dictionary <PdfName, int>(); dictionary[PdfName.CONTENTS] = num * 2 + 2; signatureAppearance.PreClose(dictionary); //PdfPKCS7 pdfPKCS = new PdfPKCS7(null, array, null, "SHA1", false); PdfPKCS7 pdfPKCS = new PdfPKCS7(null, array, null, "MD5", false); IDigest digest = DigestUtilities.GetDigest("MD5"); Stream rangeStream = signatureAppearance.GetRangeStream(); byte[] array2 = new byte[8192]; int length; while ((length = rangeStream.Read(array2, 0, array2.Length)) > 0) { digest.BlockUpdate(array2, 0, length); } byte[] array3 = new byte[digest.GetDigestSize()]; digest.DoFinal(array3, 0); DateTime now = DateTime.Now; byte[] ocsp = null; if (array.Length >= 2) { string oCSPURL = PdfPKCS7.GetOCSPURL(array[0]); if (oCSPURL != null && oCSPURL.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(array[0], array[1], oCSPURL); } } byte[] authenticatedAttributeBytes = pdfPKCS.GetAuthenticatedAttributeBytes(array3, now, ocsp); byte[] digest2 = Assinar.SignSHA1withRSA(this.card, authenticatedAttributeBytes); pdfPKCS.SetExternalDigest(digest2, array3, "RSA"); byte[] array4 = new byte[num]; byte[] encodedPKCS = pdfPKCS.GetEncodedPKCS7(array3, now, null, ocsp); pkcs7 = encodedPKCS; Array.Copy(encodedPKCS, 0, array4, 0, encodedPKCS.Length); if (num + 2 < encodedPKCS.Length) { throw new ApplicationException("Não há espaço suficiente para assinatura."); } PdfDictionary pdfDictionary = new PdfDictionary(); pdfDictionary.Put(PdfName.CONTENTS, new PdfString(array4).SetHexWriting(true)); signatureAppearance.Close(pdfDictionary); //pdfStamper. return(memoryStream); }
/// <summary> /// Firma un documento /// </summary> /// <param name="Source">Documento origen</param> /// <param name="Target">Documento destino</param> /// <param name="Certificate">Certificado a utilizar</param> /// <param name="Reason">Razón de la firma</param> /// <param name="Location">Ubicación</param> /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param> public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign) { X509CertificateParser objCP = new X509CertificateParser(); X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; PdfReader objReader = new PdfReader(Source); PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0'); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; if (AddVisibleSign) { objSA.SetVisibleSignature(new Rectangle(50, 50, 150, 100), 2, null); } objSA.SignDate = DateTime.Now; objSA.SetCrypto(null, objChain, null, null); objSA.Reason = Reason; objSA.Location = Location; objSA.Acro6Layers = true; objSA.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); objSignature.Date = new PdfDate(objSA.SignDate); objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN"); if (objSA.Reason != null) { objSignature.Reason = objSA.Reason; } if (objSA.Location != null) { objSignature.Location = objSA.Location; } objSA.CryptoDictionary = objSignature; int intCSize = 4000; Hashtable objTable = new Hashtable(); objTable[PdfName.CONTENTS] = intCSize * 2 + 2; objSA.PreClose(objTable); HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider(); Stream objStream = objSA.RangeStream; int intRead = 0; byte[] bytBuffer = new byte[8192]; while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0) { objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0); } objSHA1.TransformFinalBlock(bytBuffer, 0, 0); byte[] bytPK = SignMsg(objSHA1.Hash, Certificate, false); byte[] bytOut = new byte[intCSize]; PdfDictionary objDict = new PdfDictionary(); Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length); objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true)); objSA.Close(objDict); }
private ActionResult SignPdfFile(PdfStamper stamper, IJob job) { Signing s = job.Profile.PdfSettings.Signing; //Leave without signing //WEG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (!s.Enable) { if (stamper != null) { stamper.Close(); return(new ActionResult()); } Logger.Error("Could not create Stamper for Encryption, without Signing"); return(new ActionResult(ActionId, 104)); } //Continue for Signing s.CertificationFile = Path.GetFullPath(s.CertificationFile); if (IsValidCertificatePassword(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + s.CertificationFile + "' is wrong."); stamper.Close(); return(new ActionResult(ActionId, 105)); } if (CertificateHasPrivateKey(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + s.CertificationFile + "' has no private key."); stamper.Close(); return(new ActionResult(ActionId, 106)); } var fsCert = new FileStream(s.CertificationFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, job.Passwords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; X509CertificateEntry[] x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (int k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (s.TimeServerUrl.Trim() != "") //Timeserver with LogIn? { tsc = new TSAClientBouncyCastle(s.TimeServerUrl /*, TimeServerLogonName, TimeServerLogonPassword*/); } PdfSignatureAppearance sap = stamper.SignatureAppearance; if (tsc == null) { sap.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { sap.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } sap.Reason = s.SignReason; sap.Contact = s.SignContact; sap.Location = s.SignLocation; if (s.DisplaySignatureInPdf) { int signPage = SignPageNr(job); sap.SetVisibleSignature(new Rectangle(s.LeftX, s.LeftY, s.RightX, s.RightY), signPage, null); } var 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; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = sap.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } DateTime cal = sap.SignDate; byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); return(new ActionResult()); }
private void SignUsingEstEIDCard2(string filename, string outfile) { statusHandler(Resources.VERIFYING_DOCUMENT, false); AcroFields af = this.reader.AcroFields; ArrayList names = af.GetSignatureNames(); bool nextRevision = ((names != null) && (names.Count > 0)); // already signed ? if (nextRevision) { // pick always first signature string name = (string)names[0]; PdfPKCS7 pkc7 = af.VerifySignature(name); bool verify = pkc7.Verify(); if (!verify) { string who = PdfPKCS7.GetSubjectFields(pkc7.SigningCertificate).GetField("CN"); throw new DocVerifyException(Resources.DOC_VERIFY_FAILED + who); } } statusHandler(Resources.CONNECTING_SMARTCARD, false); // open EstEID EstEIDReader estEidReader = new EstEIDReader(); string pkcs11_lib = conf.PKCS11DriverPath; bool b = estEidReader.Open(pkcs11_lib); if (b == false) { throw new Exception(Resources.PKCS11_OPEN); } statusHandler(Resources.READ_CERTS, false); PKCS11Signer signer = LocateSigner(estEidReader); Org.BouncyCastle.X509.X509Certificate[] chain = X509Utils.LoadCertificate(signer.Cert.RawData); statusHandler(Resources.VERIFYING_OCSP, false); OCSPClientEstEID ocspClient = OCSPClient(chain[0]); if (ocspClient == null) { throw new Exception(this.lastError); } byte[] ocsp = ocspClient.GetEncoded(); if (ocsp == null) { throw new RevocationException(ocspClient.lastError); } X509Certificate2 card = signer.Cert; Oid oid = card.SignatureAlgorithm; if (oid.Value != PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { throw new Exception(Resources.INVALID_CERT); } PdfReader reader = new PdfReader(filename); Document document = new Document(reader.GetPageSizeWithRotation(1)); PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(outfile, FileMode.Create), '\0', null, nextRevision); if (metadata != null) { stp.XmpMetadata = metadata.getStreamedMetaData(); } PdfSignatureAppearance sap = stp.SignatureAppearance; if (appearance.Visible) { if (appearance.SigLocation.UseSector) { appearance.SigLocation.Bounds = document.PageSize; } sap.SetVisibleSignature(appearance.SigLocation, (int)appearance.Page, null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Reason = (appearance.Reason.Length > 0) ? appearance.Reason : null; sap.Location = (appearance.Location.Length > 0) ? appearance.Location : null; sap.Contact = (appearance.Contact.Length > 0) ? appearance.Contact : null; sap.Acro6Layers = true; sap.Render = appearance.SignatureRender; sap.Layer2Text = appearance.SignatureText(sap.SignDate, chain[0]); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, 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; } if (sap.Contact != null) { dic.Contact = sap.Contact; } sap.CryptoDictionary = dic; sap.SetExternalDigest(new byte[SIGNATURE_LENGTH], new byte[Digest.SHA1_LENGTH], "RSA"); // expect 6K to be enough if TSA response, else 2K ? int csize = (stamp != null) ? 1024 * 6 : 1024 * 2; Hashtable exc = new Hashtable(); exc[PdfName.CONTENTS] = csize * 2 + 2; sap.PreClose(exc); // compute hash based on PDF bytes byte[] digest = ComputeHash(estEidReader, sap); statusHandler(Resources.ADD_SIGNATURE, false); // sign hash byte[] rsadata = EstEIDCardSign(estEidReader, signer, digest); // if null, user requested Cancel if (rsadata == null) { throw new Exception(Resources.CARD_INTERNAL_ERROR); } // create PKCS#7 envelope PdfPKCS7 pk7 = new PdfPKCS7(null, chain, null, "SHA1", true); pk7.SetExternalDigest(rsadata, digest, "RSA"); byte[] pk = pk7.GetEncodedPKCS7(); // user wants to add TSA response ? if (stamp != null && pk != null) { statusHandler(Resources.TSA_REQUEST, false); pk = TimestampAuthorityResponse(estEidReader, pk); } // PKCS#7 bytes too large ? if (pk.Length >= csize) { throw new Exception(Resources.MEMORY_ERROR); } 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); }
private static void SetSigCryptoFromCipherParam(PdfSignatureAppearance sigAppearance, ICipherParameters key, X509Certificate[] chain) { sigAppearance.SetCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); }
public void Button3Click(object sender, System.EventArgs e) { if (inputBox.Text != null) { string filePDF = inputBox.Text; try { X509Certificate2 card = GetCertificate(); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) }; //ricreo il percorso con il nome del novo file string file = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")).ToLowerInvariant(); string NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf".ToLowerInvariant(); PdfReader reader = new PdfReader(filePDF); PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked); PdfSignatureAppearance sap = stp.SignatureAppearance; if (tsaCbx.Checked) { ITSAClient tsc = new TSAClientBouncyCastle(TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } if (SigVisible.Checked) { sap.Reason = cbRagioneSingolo.Text; sap.Contact = Contacttext.Text; sap.Location = Locationtext.Text; if (sigImgBox.Image != null) { MemoryStream ms = new MemoryStream(); sigImgBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); sap.Image = ms.ToArray() == null ? null : iTextSharp.text.Image.GetInstance(ms.ToArray()); ms.Close(); } sap.SetVisibleSignature(new iTextSharp.text.Rectangle((float)sigPosX.Value, (float)sigPosY.Value, (float)sigPosX.Value + (float)sigWidth.Value, (float)sigPosY.Value + (float)sigHeight.Value), Convert.ToInt32(numberOfPagesUpDown.Value), null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.Description; //.NameAndDescription; PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); 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; } if (sap.Contact != null) { dic.Contact = sap.Contact; } sap.CryptoDictionary = dic; int contentEstimated = 15000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); IDigest messageDigest = DigestUtilities.GetDigest("SHA256"); //add Stream s = sap.GetRangeStream(); MemoryStream ss = new MemoryStream(); int read = 0; byte[] buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { ss.Write(buff, 0, read); messageDigest.BlockUpdate(buff, 0, read); //add } //-------------------------------------------- byte[] hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); DateTime cal = DateTime.Now; byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); MessageBox.Show(ocsp.ToString()); } } //------------------------------------------------------------------- //TEST TIMESTAMP CON BOUNCYCASTLE //------------------------------------------------------------------- /* * TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); * // Dummy request * TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100)); * byte[] reqData = request.GetEncoded(); * HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create("http://localhost:8080/signserver/process?workerId=1"); * httpReq.Method = "POST"; * httpReq.ContentType = "application/timestamp-query"; * httpReq.ContentLength = reqData.Length; * // Write the request content * Stream reqStream = httpReq.GetRequestStream(); * reqStream.Write(reqData, 0, reqData.Length); * reqStream.Close(); * HttpWebResponse httpResp = (HttpWebResponse) httpReq.GetResponse(); * // Read the response * Stream respStream = new BufferedStream(httpResp.GetResponseStream()); * TimeStampResponse response = new TimeStampResponse(respStream); * respStream.Close(); * //MessageBox.Show(response.TimeStampToken.TimeStampInfo.GenTime.ToString()); */ //------------------------------------------------------------------- //TEST TIMESTAMP CON BOUNCYCASTLE //------------------------------------------------------------------- //===================================QUI FIRMO byte[] pk; if (tsaCbx.Checked) { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } else { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, "", "", ""); } //-------------------------------------------- byte[] outc = new byte[contentEstimated]; PdfDictionary dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sap.Close(dic2); MessageBox.Show("File firmato correttamente", "Operazione Completata"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
public override byte[] Sign(byte[] pdf, bool detached) { if (_certificate == null) { _certificate = GetCertificate(); if (_certificate == null) { throw new Exceptions.CertificateNotFoundException(this.CertificateSelector); } _chain = GetChain(); } PdfReader reader = new PdfReader(pdf); using (MemoryStream result = new MemoryStream()) { PdfStamper stp = PdfStamper.CreateSignature(reader, result, '\0'); PdfSignatureAppearance sap = stp.SignatureAppearance; sap.SetCrypto(null, _chain, null, null); this.OnPrepareSignatureEvent( new CertificateInfo { CN = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("CN"), SerialNumber = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("SN") } , sap); this.PrepareAppareance(sap); PdfSignature dic = null; if (detached) { dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); } else { dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); } dic.Date = new PdfDate(sap.SignDate); dic.Name = PdfPKCS7.GetSubjectFields(_chain[0]).GetField("CN"); this.PrepareSignature(dic, sap); sap.CryptoDictionary = dic; int csize = detached ? 10000 : 4000; Hashtable exc = new Hashtable(); exc[PdfName.CONTENTS] = csize * 2 + 2; sap.PreClose(exc); byte[] msg = null; if (detached) { msg = GetMsgDetached(sap); } else { msg = GetMsgHashed(sap); } byte[] pk = SignMsg(msg, _certificate, detached); 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); return(result.ToArray()); } }
public byte[] SignDetached(byte[] data, int certIndex, string storeLocation, string storeName, string location, string reason, int position) { MemoryStream outMs = new MemoryStream(); // X509Certificate2 card = GetCertificate(certIndex, storeLocation, storeName); // FAILLACE qui tocca fornire il certificato? X509Certificate2 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) }; PdfReader reader = new PdfReader(data); PdfStamper stp = null; bool isPades = IsPdfPades(reader); bool isPdfA = IsPDFA(reader); if (isPades) //se pades vado in append. { stp = PdfStamper.CreateSignature(reader, outMs, '\0', null, true); } else { stp = PdfStamper.CreateSignature(reader, outMs, '\0'); } if (isPdfA) { stp.Writer.PDFXConformance = PdfWriter.PDFA1A; } PdfSignatureAppearance sap = stp.SignatureAppearance; Rectangle pageSize = reader.GetPageSize(1); Rectangle signatureRect = setPosition(position, pageSize); sap.SetVisibleSignature(signatureRect, 1, null); sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Reason = reason; sap.Location = location; sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; //così appare solo il testo che voglio io. sap.Layer2Text = "Test"; sap.Render = PdfSignatureAppearance.SignatureRender.Description; if (isPdfA) { //BaseFont bf = BaseFont.CreateFont(@"c:\windows\fonts\arial.ttf", BaseFont.WINANSI, true); //forse va sistemato questo path. Stream fo = BaseFont.GetResourceStream("DPA.DigitalSignature.Itextsharp.iTextSharp.text.pdf.fonts.Helvetica.afm"); byte[] fb = new BinaryReader(fo).ReadBytes((int)fo.Length); //BaseFont bf1 = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, true); BaseFont bf = BaseFont.CreateFont("helvetica.afm", BaseFont.WINANSI, true, false, fb, fb); sap.Layer2Font = new Font(bf); } PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); 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 = 10000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = csize * 2 + 2; Hashtable dict_hasht = new Hashtable(exc); sap.PreClose(dict_hasht); Stream s = sap.RangeStream; MemoryStream ss = new MemoryStream(); int read = 0; byte[] buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { ss.Write(buff, 0, read); } byte[] pk = FirmaFileBouncy(ss.ToArray(), card); //pk = SignMsg(ss.ToArray(), card, true); 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, true); outMs.Position = 0; BinaryReader br = new BinaryReader(outMs); byte[] retval = br.ReadBytes((int)outMs.Length); outMs.Close(); return(retval); }
public static bool PDFSign(string inputfile, string outputfile, STabCard sTabCard) { try { Certificate cert = new Certificate(); int i = 3; for (i = 3; i > 0; i--) { if (SystemSingleton.CurrentSession.CertPassword == "") { SetPassword window = new SetPassword(); window.ShowDialog(); } try { cert = new Certificate(SystemSingleton.Configuration.CertificatePath, SystemSingleton.CurrentSession.CertPassword); break; } catch { EnvironmentHelper.SendDialogBox( (string)SystemSingleton.Configuration.mainWindow.FindResource("m_CertPassError") + " " + (i - 1), "Certificate/Password Error" ); SystemSingleton.CurrentSession.CertPassword = ""; } } if (i == 0) { EnvironmentHelper.SendDialogBox( (string)SystemSingleton.Configuration.mainWindow.FindResource("m_CantSaveFile"), "File Error" ); return(false); } MetaData MD = new MetaData(); MD.Author = SystemSingleton.CurrentSession.FullName; MD.Title = sTabCard.Card.Task.Number; MD.Subject = sTabCard.Card.DocType.Caption; MD.Keywords = sTabCard.Card.Task.Commentary; MD.Creator = sTabCard.Card.From.FullName; MD.Producer = SystemSingleton.Configuration.CompanyName; PdfReader reader = new PdfReader(inputfile); PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outputfile, FileMode.Create, FileAccess.Write), '\0', null, true); st.MoreInfo = MD.getMetaData(); st.XmpMetadata = MD.getStreamedMetaData(); PdfSignatureAppearance sap = st.SignatureAppearance; sap.SetCrypto(cert.Akp, cert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.Reason = "Completition"; sap.Contact = MD.Producer; sap.Location = SystemSingleton.Configuration.CompanyLocation; if (SystemSingleton.Configuration.SignVisible) { sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null); } st.Close(); return(true); } catch { EnvironmentHelper.SendDialogBox( (string)SystemSingleton.Configuration.mainWindow.FindResource("m_CantSaveFile"), "File Error" ); return(false); } }
public bool FirmarPDF(string pdfOriginal, string pdfFirmado, SysX509.X509Certificate2 certificado, string imagenFirma, bool firmaVisible, float puntoEsquinaInferiorIzquierdaX, float puntoEsquinaInferiorIzquierdaY, float puntoEsquinaSuperiorDerechaX, float puntoEsquinaSuperiorDerechaY, eTipoPagina paginaFirma, int pagina) { int numPagina = 0; try { X509CertificateParser objCP = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificado.RawData) }; PdfReader objReader = new PdfReader(pdfOriginal); PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(pdfFirmado, FileMode.Create), '\0'); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; if (paginaFirma == eTipoPagina.Ultima) { numPagina = objReader.NumberOfPages; } else { if (pagina <= objReader.NumberOfPages) { numPagina = pagina; } else if (pagina > objReader.NumberOfPages) { numPagina = objReader.NumberOfPages; } else if (pagina < 1) { numPagina = 1; } } if (firmaVisible) { Rectangle rect = new Rectangle(puntoEsquinaInferiorIzquierdaX, puntoEsquinaInferiorIzquierdaY, puntoEsquinaSuperiorDerechaX, puntoEsquinaSuperiorDerechaY); objSA.SetVisibleSignature(rect, numPagina, null); } objSA.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; objSA.SignDate = DateTime.Now; objSA.SetCrypto(null, objChain, null, null); objSA.Acro6Layers = true; objSA.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; //objSA.SignatureGraphic = iTextSharp.text.Image.GetInstance(imagenFirma); // PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); objSignature.Date = new PdfDate(objSA.SignDate); objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN"); if (objSA.Reason != null) { objSignature.Reason = objSA.Reason; } if (objSA.Location != null) { objSignature.Location = objSA.Location; } if (objSA.Contact != null) { objSignature.Contact = objSA.Contact; } objSA.CryptoDictionary = objSignature; int intCSize = 4000; Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>(); objTable[PdfName.CONTENTS] = intCSize * 2 + 2; objSA.PreClose(objTable); HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider(); Stream objStream = objSA.RangeStream; int intRead = 0; byte[] bytBuffer = new byte[8192]; while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0) { objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0); } objSHA1.TransformFinalBlock(bytBuffer, 0, 0); byte[] bytPK = GenerarFirmar(objSHA1.Hash, certificado, false); byte[] bytOut = new byte[intCSize]; PdfDictionary objDict = new PdfDictionary(); Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length); objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true)); objSA.Close(objDict); return(true); } catch { throw; } }
private void signDetached(PdfSignatureAppearance sap) { sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; sap.SetCrypto(_asymmetricKeyParameter, _chain, null, PdfSignatureAppearance.SelfSigned); }
/// <summary> /// Firma un documento /// </summary> /// <param name="Source">Documento origen</param> /// <param name="Target">Documento destino</param> /// <param name="Certificate">Certificado a utilizar</param> /// <param name="Reason">Razón de la firma</param> /// <param name="Location">Ubicación</param> /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param> public void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, DatosPersonales datos) { X509CertificateParser objCP = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; PdfReader objReader = new PdfReader(Source); PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; if (AddVisibleSign) { objSA.SetVisibleSignature(new Rectangle(100f, objReader.XrefSize, 500, 100), 1, null); } objSA.SignDate = DateTime.Now; objSA.SetCrypto(null, objChain, null, null); objSA.Reason = Reason; objSA.Location = Location; objSA.Acro6Layers = true; objSA.Render = PdfSignatureAppearance.SignatureRender.NameAndDescription; PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); objSignature.Date = new PdfDate(objSA.SignDate); objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN"); if (objSA.Reason != null) { objSignature.Reason = objSA.Reason; } if (objSA.Location != null) { objSignature.Location = objSA.Location; } objSA.CryptoDictionary = objSignature; int intCSize = 4000; // Hashtable objTable = new Hashtable(); // objTable[PdfName.CONTENTS] = intCSize * 2 + 2; Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>(); PdfName pdfname = new PdfName("firma"); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. objTable.Add(pdfname, intCSize * 2 + 2); objSA.PreClose(objTable); HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider(); Stream objStream = objSA.RangeStream; int intRead = 0; byte[] bytBuffer = new byte[8192]; while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0) { objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0); } objSHA1.TransformFinalBlock(bytBuffer, 0, 0); byte[] bytPK = SignMsg(objSHA1.Hash, Certificate, false); byte[] bytOut = new byte[intCSize]; PdfDictionary objDict = new PdfDictionary(); Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length); objDict.Put(pdfname, new PdfString(bytOut).SetHexWriting(true)); try { objSA.Close(objDict); } catch (Exception ex) { } }
public static void Sign(Signature signature, PDFMetadata metadata, string input, string output) { if (signature == null) { throw new NullReferenceException(); } if (signature.Store == null) { throw new NullReferenceException(); } /* Get Store Private Key and Certificate Chain */ var name = GetPrivateKeyName(signature.Store); if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException("No private key available"); } var privateKey = signature.Store.GetKey(name).Key; X509Certificate[] certificateChain = GetCertificateChain(signature.Store, name); if (certificateChain == null) { throw new InvalidOperationException("No private key available"); } /* Prepare file input/output */ var reader = new PdfReader(input, null); var outputFile = new FileStream(output, FileMode.Create, FileAccess.Write); var stamper = PdfStamper.CreateSignature(reader, outputFile, '\0', null, true); stamper.MoreInfo = metadata.InfoHashtable; stamper.XmpMetadata = metadata.XmpMetadata; /* Create Siganture Appearance */ PdfSignatureAppearance signatureAppearance = CreateSignatureAppearance(stamper, signature); signatureAppearance.SetCrypto(privateKey, certificateChain, null, PdfSignatureAppearance.WINCER_SIGNED); signatureAppearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS; PdfSignature pdfSignature = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); pdfSignature.Reason = signatureAppearance.Reason; pdfSignature.Location = signatureAppearance.Location; pdfSignature.Contact = signatureAppearance.Contact; pdfSignature.Date = new PdfDate(signatureAppearance.SignDate); signatureAppearance.CryptoDictionary = pdfSignature; // Preallocate excluded byte-range for the signature content (hex encoded) var excludedByteRange = new Dictionary <PdfName, int> (); excludedByteRange[PdfName.CONTENTS] = ContentEstimated * 2 + 2; signatureAppearance.PreClose(new Hashtable(excludedByteRange)); // Sign the document PKCS7SignDocument(privateKey, certificateChain, signatureAppearance, "SHA-256"); }
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.GetRangeStream(); 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().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url); } } 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(); }
public bool Sign(string iSignReason, string iSignContact, string iSignLocation, bool visible, string iImageString) { string vCertificatesPath = "CN=" + CertificatesName; #region Geting Certs X509Store store = new X509Store(_storedName, _storedLocation); StorePermission sp = new StorePermission(PermissionState.Unrestricted); sp.Flags = StorePermissionFlags.OpenStore; sp.Assert(); store.Open(OpenFlags.MaxAllowed); X509Certificate2 cert = null; int i = 0; while ((i < store.Certificates.Count) && (cert == null)) { if (store.Certificates[i].Subject.ToUpper().Contains(vCertificatesPath)) { cert = store.Certificates[i]; } else { i++; } } store.Close(); if (cert == null) { throw new CryptographicException("Certificate is NULL. Certificate can not be found"); } Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); var cerRawData = cert.RawData; var certificates = cp.ReadCertificate(cerRawData); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certificates }; var chainFirst = GetChainBouncyCastle(cert); #endregion Geting Certs PdfReader reader = null; if (string.IsNullOrEmpty(inputPdfFileString)) { reader = new PdfReader(inputPdfStream); } else { reader = new PdfReader(this.inputPdfFileString); } if (outputPdfStream == null && string.IsNullOrEmpty(outputPdfFileString) == false) { outputPdfStream = new FileStream(this.outputPdfFileString, FileMode.OpenOrCreate, FileAccess.Write); } if (reader != null && outputPdfStream != null) { #region Standard Signing PdfStamper vStamper = PdfStamper.CreateSignature(reader, outputPdfStream, '\0', null, false); vStamper.MoreInfo = this.settingMetadata.GetMetaDataHashtable(); vStamper.XmpMetadata = this.settingMetadata.GetStreamedMetaData(); PdfSignatureAppearance vSignatureAppearance = vStamper.SignatureAppearance; vSignatureAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); vSignatureAppearance.SignDate = SignDate; vSignatureAppearance.Reason = iSignReason; vSignatureAppearance.Contact = iSignContact; vSignatureAppearance.Location = iSignLocation; vSignatureAppearance.Acro6Layers = true; vSignatureAppearance.Render = PdfSignatureAppearance.SignatureRender.Description; if (visible) { vSignatureAppearance.SetVisibleSignature( new iTextSharp.text.Rectangle(ImageLocation.Width, ImageLocation.Height, ImageLocation.Width + ImageSize.Width, ImageLocation.Height + ImageSize.Height), 1, null); if (File.Exists(iImageString)) { iTextSharp.text.Image vImage = iTextSharp.text.Image.GetInstance(iImageString); vSignatureAppearance.Image = vImage; } } vSignatureAppearance.SetExternalDigest(new byte[128], new byte[20], "RSA"); #endregion Standard Signing #region Self Signed Mode PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1); dic.Date = new PdfDate(vSignatureAppearance.SignDate); var vName = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); dic.Name = vName; if (vSignatureAppearance.Reason != null) { dic.Reason = vSignatureAppearance.Reason; } if (vSignatureAppearance.Location != null) { dic.Location = vSignatureAppearance.Location; } vSignatureAppearance.CryptoDictionary = dic; int csize = 4000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = csize * 2 + 2; vSignatureAppearance.PreClose(new Hashtable(exc)); HashAlgorithm sha = new SHA1CryptoServiceProvider(); Stream s = vSignatureAppearance.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, cert, 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)); vSignatureAppearance.Close(dic2); #endregion Self Signed Mode if (vSignatureAppearance.IsPreClosed() == false) { vStamper.Close(); } reader.Close(); return(true); } return(false); }