/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = DigestUtilities.GetDigest(tsa.GetDigestAlgorithm()); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken = tsa.GetTimeStampToken(tsImprint); if (contentEstimated + 2 < tsToken.Length) throw new Exception("Not enough space"); byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
private static void SetSigPosition(PdfSignatureAppearance sigAppearance, int oldSigCount) { //Note: original formula from QuangNgV, ll = lower left, ur = upper right, coordinates are calculated relative from the lower left of the pdf page float llx = (100 + 20) * (oldSigCount % 5), lly = (25 + 20) * (oldSigCount / 5), urx = llx + 100, ury = lly + 25; sigAppearance.SetVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, null); }
private void signPDF(int llx, int lly, int urx, int ury) { // Do something interesting with unsigned PDF document FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath); //Assert.IsTrue(unsignedPdfInfo.Length > 0); // Specify path to the unmanaged PCKS#11 library string libraryPath = @"C:\Windows\System32\cvP11.dll"; // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified. string tokenSerial = @"910e21b0da172e34"; // Specify label of of the token that contains signing key. May be null if tokenSerial is specified string tokenLabel = @"SuisseID"; // Specify PIN for the token string pin = "091011"; // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified. string ckaLabel = null; // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified. string ckaId = "6D808CE0BF9C368FB0AD28E24366F646BA0B3F67"; // Specify hash algorihtm used for the signature creation HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, HashAlgorithm.SHA256)) { // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // All certificates stored on the token can be usually read with GetAllCertificates() method List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; signatureAppearance.SignatureGraphic = iTextSharp.text.Image.GetInstance("logo_sign.png"); signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle((float)llx, (float)lly, (float)urx, (float)ury), 1, null); MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); //MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } // Do something interesting with the signed PDF document FileInfo signedPdfInfo = new FileInfo(signedPdfPath); //Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length); }
public string GenerateHash() { string Reason = "Motivo"; string Location = "Localização"; string Contact = "Contato"; string signatureFieldName = null; appearance.SetVisibleSignature(new Rectangle(500, 150, 400, 200), 1, signatureFieldName); appearance.SignDate = DateTime.Now; appearance.Reason = Reason; appearance.Location = Location; appearance.Contact = Contact; StringBuilder buf = new StringBuilder(); buf.Append("Digitally signed by"); buf.Append("\n"); buf.Append(userName); buf.Append("\n"); buf.Append("Date: " + appearance.SignDate); appearance.Layer2Text = buf.ToString(); appearance.Acro6Layers = true; appearance.CertificationLevel = 0; PdfSignature dic = GeneratePdfSignature(); appearance.CryptoDictionary = dic; Dictionary <PdfName, int> exclusionSizes = new Dictionary <PdfName, int>(); exclusionSizes.Add(PdfName.CONTENTS, (RESERVED_SPACE_SIGNATURE * 2) + 2); appearance.PreClose(exclusionSizes); HashAlgorithm sha = new SHA256CryptoServiceProvider(); Stream s = appearance.GetRangeStream(); int read = 0; byte[] buff = new byte[0x2000]; while ((read = s.Read(buff, 0, 0x2000)) > 0) { sha.TransformBlock(buff, 0, read, buff, 0); } sha.TransformFinalBlock(buff, 0, 0); StringBuilder hex = new StringBuilder(sha.Hash.Length * 2); foreach (byte b in sha.Hash) { hex.AppendFormat("{0:x2}", b); } return(hex.ToString()); }
public static void DigitalSign() { PdfReader reader = new PdfReader(@"C:\workspace\PDFDigitalSign\Resource\Result1.pdf"); using (FileStream fout = new FileStream(@"C:\workspace\PDFDigitalSign\Resource\Result2.pdf", FileMode.Create, FileAccess.ReadWrite)) { // appearance PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true); PdfSignatureAppearance appearance = stamper.SignatureAppearance; //appearance.Reason = SignReason; //appearance.Location = SignLocation; appearance.SignDate = DateTime.Now.Date; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 50 + 200, 50 + 100), 1, null);//.IsInvisible // Custom text and background image appearance.Image = iTextSharp.text.Image.GetInstance(@"C:\workspace\PDFDigitalSign\Resource\sign2.png"); appearance.ImageScale = 0.6f; appearance.Image.Alignment = 300; appearance.Acro6Layers = true; StringBuilder buf = new StringBuilder(); buf.Append("Digitally Signed by "); String name = "Sidd"; buf.Append(name).Append('\n'); buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz")); string text = buf.ToString(); appearance.Layer2Text = text; var pk12 = new Pkcs12Store(new System.IO.FileStream(@"C:\workspace\PDFDigitalSign\Resource\certificate.pfx", System.IO.FileMode.Open, System.IO.FileAccess.Read), "12345678".ToCharArray()); string alias = null; foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; //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(); } }
public void EmptySignature(String src, String dest, String fieldname, IList <X509Certificate> chain) { PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, fieldname); appearance.Certificate = chain[0]; IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); MakeSignature.SignExternalContainer(appearance, external, 8192); }
public bool signSupportingDoc(string RefID, 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 = "Sign Request (Ref : " + RefID + ")"; // appearance.Location = location; (0, 0, 320, 72) Lower left conner appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(600, 0, 400, 72), PageCount, "Icsi-Vendor"); //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); } }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); sap.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = tsa.GetMessageDigest(); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken; try { tsToken = tsa.GetTimeStampToken(tsImprint); } catch (Exception e) { throw new GeneralSecurityException(e.Message); } //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande. if (contentEstimated + 2 < tsToken.Length) { throw new IOException("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
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(); } }
/// <summary> /// Initialize the PDF signature field. /// </summary> private void InitSignatureField(PdfStamper stamper) { if (_acroFieldsWorker.HasSignatureField(SignatureFieldName)) { _signatureAppearance.SetVisibleSignature(SignatureFieldName); } else { if (!string.IsNullOrWhiteSpace(SignatureFieldName) && _acroFieldsWorker.HasField(SignatureFieldName)) { var textField = _acroFieldsWorker.FieldLocationByName(SignatureFieldName); _signatureAppearance.SetVisibleSignature( textField.Rectangle, textField.Page, _signatureAppearance.GetNewSigName() ); stamper.FormFlattening = true; stamper.PartialFormFlattening(SignatureFieldName); } else if (SignatureBox != null) { _signatureAppearance.SetVisibleSignature( SignatureBox, // reader.NumberOfPages, 1, _signatureAppearance.GetNewSigName() ); stamper.FormFlattening = true; // stamper.PartialFormFlattening(SignatureFieldName); } else { throw new InvalidOperationException("field does not exist"); } } }
//schimbare functie pentru iText private string generateHash() { appearance.SetVisibleSignature(new Rectangle(500, 150, 400, 200), 1, "signature"); appearance.SignDate = DateTime.Now; appearance.Reason = "Test Licenta"; appearance.Location = "Bucuresti"; appearance.Contact = "mta"; StringBuilder buf = new StringBuilder(); buf.Append("Semnat digital de"); buf.Append("\n"); buf.Append(userName); buf.Append("\n"); buf.Append("Date: " + appearance.SignDate); appearance.Layer2Text = buf.ToString(); appearance.Acro6Layers = true; appearance.CertificationLevel = 0; PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED) { Date = new PdfDate(appearance.SignDate), Name = userName }; dic.Reason = appearance.Reason; dic.Location = appearance.Location; dic.Contact = appearance.Contact; appearance.CryptoDictionary = dic; Dictionary <PdfName, int> exclusionSizes = new Dictionary <PdfName, int>(); exclusionSizes.Add(PdfName.CONTENTS, (csize * 2) + 2); appearance.PreClose(exclusionSizes); HashAlgorithm sha = new SHA256CryptoServiceProvider(); Stream s = appearance.GetRangeStream(); int read = 0; byte[] buff = new byte[0x2000]; while ((read = s.Read(buff, 0, 0x2000)) > 0) { sha.TransformBlock(buff, 0, read, buff, 0); } sha.TransformFinalBlock(buff, 0, 0); return(System.Convert.ToBase64String(sha.Hash)); }
/// <summary> /// Firma un documento PDF /// </summary> /// <param name="Source">Path del PDF a firmar</param> /// <param name="Target">Path del PDF firmado</param> /// <param name="Certificate">Certificado para realizar la firma</param> /// <param name="Reason">Motivo</param> /// <param name="Location">Ubicación</param> /// <param name="AddVisibleSign">Indica si la firma es visible dentro del documento</param> /// <param name="AddTimeStamp">Indica si se va a añadir sello de tiempo en el documento</param> /// <param name="strTSA">TSA del sello de tiempo</param> public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, bool AddTimeStamp, string strTSA) { X509CertificateParser objCP = new X509CertificateParser(); X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; //IList<ICrlClient> crlList = new List<ICrlClient>(); //crlList.Add(new CrlClientOnline(objChain)); PdfReader objReader = new PdfReader(Source); PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true); // Creamos la apariencia PdfSignatureAppearance signatureAppearance = objStamper.SignatureAppearance; signatureAppearance.Reason = Reason; signatureAppearance.Location = Location; // Si está la firma visible: if (AddVisibleSign) { signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 300, 200), 1, null); //signatureAppearance.SetVisibleSignature(new Rectangle(100, 100, 250, 150), objReader.NumberOfPages, "Signature"); } ITSAClient tsaClient = null; IOcspClient ocspClient = null; // Si se ha añadido el sello de tiempo if (AddTimeStamp) { // ocspClient = new OcspClientBouncyCastle(); tsaClient = new TSAClientBouncyCastle(strTSA); } // Creating the signature // IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1"); // MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS); if (objReader != null) { objReader.Close(); } if (objStamper != null) { objStamper.Close(); } }
public void Sign(String src, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // 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(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
static void Main(string[] args) { //All pdf files are fetched from a particular folder string[] pdfFiles = Directory.GetFiles("PATH1", "*.pdf") .Select(Path.GetFileName) .ToArray(); string[] pdfpaths = Directory.GetFiles("PATH1", "*.pdf").ToArray(); string[] newfilepaths = new string[50]; int[] psn = new int[50]; string[] ski; for (int i = 0; i < pdfFiles.Length; i++) { psn[i] = PSNumber(pdfFiles[i]); string[] address = { @"PATH2", pdfFiles[i] }; newfilepaths[i] = Path.Combine(address); } ski = details(psn); for (int i = 0; psn[i] != 0; i++) { X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectKeyIdentifier, ski[i], true); X509Certificate2 digitalID = fcollection[0]; PdfReader reader = new PdfReader(pdfpaths[i]); PdfStamper stamper = PdfStamper.CreateSignature(reader, new FileStream(newfilepaths[i], FileMode.Create), '\0'); PdfSignatureAppearance sap = stamper.SignatureAppearance; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), 1, null); BcX509.X509Certificate bcCert = DotNetUtils.FromX509Certificate(digitalID); var chain = new List <BcX509.X509Certificate> { bcCert }; var privatekey = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(digitalID.PrivateKey).Private; IExternalSignature es = new PrivateKeySignature(privatekey, "SHA-256"); MakeSignature.SignDetached(sap, es, chain, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); store.Close(); } }
public void SignIt() { var fileStream = new FileStream("../../keystore2.pfx", FileMode.Open, FileAccess.Read); var pk12 = new Pkcs12Store(fileStream, "barantopal".ToCharArray()); fileStream.Flush(); fileStream.Close(); string alias = null; // a loop is not super need here but well because we have 1 certificate entry that corresponds to a private key foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; // reader and stamper var reader = new PdfReader(SourceFilePath); using (var fout = new FileStream(DestinationFilePath, FileMode.Create, FileAccess.ReadWrite)) { using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { // appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; //appearance.Image = new iTextSharp.text.pdf.PdfImage(); appearance.Reason = "I've written this."; appearance.Location = "Foobar"; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), 1, "Icsi-Vendor"); // digital signature IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); } } }
private static PdfSignatureAppearance GetPdfSignatureAppearance(SigningCertificates signingCertificates, PdfStamper stamper, PdfReader reader, PdfSignatureParameters parameters) { PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = ""; appearance.LocationCaption = ""; appearance.Location = ""; appearance.Layer4Text = ""; appearance.Layer2Text = GetSignatureText(signingCertificates.X509Certificate, parameters); appearance.Acro6Layers = true; Rectangle cropBox = reader.GetCropBox(parameters.SignaturePageNumber); Rectangle rectangle = GetSignatureLocation(cropBox, parameters); appearance.SetVisibleSignature(rectangle, parameters.SignaturePageNumber, parameters.SignatureName); return(appearance); }
public void Sign(String src, String dest, ICollection <X509Certificate> chain, X509Certificate2 pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) { // Creating the reader and the stamper PdfReader reader = null; PdfStamper stamper = null; FileStream os = null; try { reader = new PdfReader(src); os = new FileStream(dest, FileMode.Create); stamper = PdfStamper.CreateSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = location; appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); } finally { if (reader != null) { reader.Close(); } if (stamper != null) { stamper.Close(); } if (os != null) { os.Close(); } } }
public void Sign(string SigReason, string SigContact, string SigLocation, bool visible) { PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(this.inputPDF); //激活多签名 stamper = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0', null, true); //禁用多签名请取消该行注释,每一个新签名将覆盖旧的签名 //stamper = PdfStamper.CreateSignature(reader, new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write), '\0'); stamper.MoreInfo = metadata.getMetaData(); stamper.XmpMetadata = this.metadata.getStreamedMetaData(); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = SigReason; appearance.Contact = SigContact; appearance.Location = SigLocation; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(40, 748, 164, 780), 1, "sig"); appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; appearance.Layer2Font = new Font(BaseFont.CreateFont(@"c:/windows/fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 4); IExternalSignature pks = new PrivateKeySignature(this.myCert.Akp, DigestAlgorithms.SHA256); MakeSignature.SignDetached(appearance, pks, this.myCert.Chain, null, null, null, 0, CryptoStandard.CMS); } catch (Exception ex) { throw ex; } finally { if (reader != null) { reader.Close(); } DelectFile(this.inputPDF); } }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = DigestUtilities.GetDigest(tsa.GetDigestAlgorithm()); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken = tsa.GetTimeStampToken(tsImprint); if (contentEstimated + 2 < tsToken.Length) { throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
private static PdfSignatureAppearance GetPSA(string fieldName, PdfStamper stamper, Bitmap graphics, string reason, string location, PdfSignatureAppearance.SignatureRender renderingMode, int certLevel) { PdfSignatureAppearance psa = stamper.SignatureAppearance; psa.Acro6Layers = true; psa.SignatureGraphic = iTextSharp.text.Image.GetInstance(graphics, ImageFormat.Png); psa.Render = renderingMode; psa.CertificationLevel = certLevel; psa.Reason = reason; psa.Location = location; psa.SetVisibleSignature(fieldName); return(psa); }
public void Sign4(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // 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); // Default text and scaled background image appearance.Image = Image.GetInstance(IMG); appearance.ImageScale = -1; // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void SignPdf(string filename, string outFilename) { PdfReader reader = new PdfReader(filename); PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(outFilename, FileMode.Create, FileAccess.Write), '\0', null, true); PdfSignatureAppearance sap = st.SignatureAppearance; sap.Reason = "税单完整性"; sap.Location = "广州海关"; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(450, 100, 650, 200), 1, "sig"); sap.ImageScale = 1; sap.Layer2Text = "此文档由广州海关签名"; sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; sap.SignatureGraphic = Stamp; IExternalSignature signature = new PrivateKeySignature(PrivateKey, "SHA-256"); MakeSignature.SignDetached(sap, signature, CertChain, null, null, null, 0, CryptoStandard.CMS); }
private void addVisibleSignature(PdfSignatureAppearance signAppearance, PdfStamper stamper) { if (SignatureData.VisibleSignature == null) { return; } signAppearance.Image = string.IsNullOrEmpty(SignatureData.VisibleSignature.ImagePath) ? null : Image.GetInstance(SignatureData.VisibleSignature.ImagePath); signAppearance.Layer2Text = SignatureData.VisibleSignature.CustomText; if (SignatureData.VisibleSignature.RunDirection == null) { SignatureData.VisibleSignature.RunDirection = PdfRunDirection.LeftToRight; } signAppearance.RunDirection = (int)SignatureData.VisibleSignature.RunDirection; signAppearance.Layer2Font = SignatureData.VisibleSignature.Font.Fonts[0]; var pageNumber = SignatureData.VisibleSignature.UseLastPageToShowSignature ? stamper.Reader.NumberOfPages : SignatureData.VisibleSignature.PageNumberToShowSignature; signAppearance.SetVisibleSignature(SignatureData.VisibleSignature.Position, pageNumber, null); }
public void Sign1(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // 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); // Custom text and custom font appearance.Layer2Text = "This document was signed by Bruno Specimen"; appearance.Layer2Font = new Font(Font.FontFamily.TIMES_ROMAN); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void FillOutAndSign(String keystore, String src, String name, String fname, String value, 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); AcroFields form = stamper.AcroFields; form.SetField(fname, value); form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null); form.SetFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null); // Creating the appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SetVisibleSignature(name); // Creating the signature PrivateKeySignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS); }
public void Sign(PdfSignatureAp sigAP) { PdfReader reader = new PdfReader(this._inputPdf); FileStream fs = new FileStream(this._outputPdf, FileMode.Create, FileAccess.Write); PdfStamper st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi); try { PdfSignatureAppearance sap = st.SignatureAppearance; sap.SignDate = DateTime.Now; 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; IOcspClient ocsp = new OcspClientBouncyCastle(); PrivateKeySignature pks = new PrivateKeySignature(_cert.Akp, "SHA1"); MakeSignature.SignDetached(sap, pks, _cert.Chain, null, ocsp, null, 0, CryptoStandard.CMS); } finally { st.Close(); fs.Close(); } }
public void Sign2(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // 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); // Custom text, custom font, and right-to-left writing appearance.Layer2Text = "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628"; appearance.RunDirection = PdfWriter.RUN_DIRECTION_RTL; appearance.Layer2Font = new Font(BaseFont.CreateFont("C:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 12); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location, PdfSignatureAppearance.RenderingMode renderingMode, Image image) { // 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.Layer2Text = "Signed on " + DateTime.Now; appearance.SignatureRenderingMode = renderingMode; appearance.SignatureGraphic = image; // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }
/// <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="destinationDocument">The path at which the signed pdf document should be generated</param> /// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param> /// <param name="pfxKeyPass">The password for the private key</param> /// <param name="reasonForSigning">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 void SignPdfFile(string sourceDocument, string destinationDocument, SignInfo i) { using (var cpfxFile = new FileStream(i.pfxFilePath, FileMode.Open, FileAccess.Read)) { Pkcs12Store pk12 = new Pkcs12Store(cpfxFile, i.pfxKeyPass.ToCharArray()); string alias = null; foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; using (var reader = new PdfReader(sourceDocument)) using (var fout = new FileStream(destinationDocument, FileMode.Create, FileAccess.ReadWrite)) using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { stamper.SetEncryption(i.docPass, i.docPass, PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH128BITS); var img = new iTextSharp.text.Jpeg(new Uri(i.signImagePath)); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Image = img; appearance.Reason = i.reasonForSigning; appearance.Location = i.location; const float x = 20, y = 10; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + img.Width, y + img.Width), 1, "Icsi-Vendor"); IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); } } }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); sap.SetVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary<PdfName,int> exc = new Dictionary<PdfName,int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = tsa.GetMessageDigest(); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken; try { tsToken = tsa.GetTimeStampToken(tsImprint); } catch(Exception e) { throw new GeneralSecurityException(e.Message); } //TODO jbonilla Validar para el TSA de Certificado que devuelve un valor muy grande. if (contentEstimated + 2 < tsToken.Length) throw new IOException("Not enough space"); byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
/*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 src, String name, String dest, ICollection <X509Certificate> chain, ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter, String reason, String location) { // 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); // Creating the appearance for layer 0 PdfTemplate n0 = appearance.GetLayer(0); float x = n0.BoundingBox.Left; float y = n0.BoundingBox.Bottom; float width = n0.BoundingBox.Width; float height = n0.BoundingBox.Height; n0.SetColorFill(BaseColor.LIGHT_GRAY); n0.Rectangle(x, y, width, height); n0.Fill(); // Creating the appearance for layer 2 PdfTemplate n2 = appearance.GetLayer(2); ColumnText ct = new ColumnText(n2); ct.SetSimpleColumn(n2.BoundingBox); Paragraph p = new Paragraph("This document was signed by Bruno Specimen."); ct.AddElement(p); ct.Go(); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter); }