public void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, PdfSignatureAppearance.RenderingMode renderingMode, ImageData image) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); // Create the signature appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(reason); appearance.SetLocation(location); // This name corresponds to the name of the field that already exists in the document. signer.SetFieldName(name); appearance.SetLayer2Text("Signed on " + DateTime.Now); // Set the rendering mode for this signature. appearance.SetRenderingMode(renderingMode); // Set the Image object to render when the rendering mode is set to RenderingMode.GRAPHIC // or RenderingMode.GRAPHIC_AND_DESCRIPTION. appearance.SetSignatureGraphic(image); PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm); // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); // Create the signature appearance Rectangle rect = new Rectangle(36, 648, 200, 100); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance .SetReason(reason) .SetLocation(location) // Specify if the appearance before field is signed will be used // as a background for the signed field. The "false" value is the default value. .SetReuseAppearance(false) .SetPageRect(rect) .SetPageNumber(1); signer.SetFieldName("sig"); IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter); }
static void SimpleSignature() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); using (var document = PdfDocument.Load("Reading.pdf")) { // Add an invisible signature field to the PDF document. var signatureField = document.Form.Fields.AddSignature(); // Get a digital ID from PKCS#12/PFX file. var digitalId = new PdfDigitalId("GemBoxRSA1024.pfx", "GemBoxPassword"); // Create a PDF signer that will create the digital signature. var signer = new PdfSigner(digitalId); // Adobe Acrobat Reader currently doesn't download certificate chain // so we will also embed certificate of intermediate Certificate Authority in the signature. // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647) signer.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("GemBoxRSA.crt") }, null, null); // Initiate signing of a PDF file with the specified signer. signatureField.Sign(signer); // Finish signing of a PDF file. document.Save("Digital Signature.pdf"); } }
public static void AddTextSignature2PDF() { //Please repace the trial key from trial-license.txt in download package //This license registration line need to be at very beginning of our other code LicenseManager.SetKey("trial key"); //Input your certificate and password PdfCertificate cert = new PdfCertificate("test.pfx", "iditect"); PdfSigner signer = new PdfSigner("sample.pdf", cert); //Set signature information signer.SignatureInfo.Contact = "123456789"; signer.SignatureInfo.Reason = "Sign by iDiTect"; signer.SignatureInfo.Location = "World Wide Web"; //Field name need to be unique in the same pdf document signer.SignatureInfo.FieldName = "iDiTect Sign Field"; //Sign in target page signer.SignatureInfo.PageId = 0; //Sign in target area signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50); signer.SignatureAlgorithm = SignatureAlgorithm.SHA256; signer.SignatureType = SignatureType.Text; signer.Sign("signed.pdf"); }
static void PAdES_B_B() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); using (var document = PdfDocument.Load("Reading.pdf")) { // Add a visible signature field to the first page of the PDF document. var signatureField = document.Form.Fields.AddSignature(document.Pages[0], 300, 500, 250, 50); // Get a digital ID from PKCS#12/PFX file. var digitalId = new PdfDigitalId("GemBoxECDsa521.pfx", "GemBoxPassword"); // Create a PDF signer that will create PAdES B-B level signature. var signer = new PdfSigner(digitalId); // PdfSigner should create CAdES-equivalent signature. signer.SignatureFormat = PdfSignatureFormat.CAdES; // Adobe Acrobat Reader currently doesn't download certificate chain // so we will also embed certificate of intermediate Certificate Authority in the signature. // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647) signer.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("GemBoxECDsa.crt") }, null, null); // Make sure that all properties specified on PdfSigner are according to PAdES B-B level. signer.SignatureLevel = PdfSignatureLevel.PAdES_B_B; // Initiate signing of a PDF file with the specified signer. signatureField.Sign(signer); // Finish signing of a PDF file. document.Save("PAdES B-B.pdf"); } }
protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location, Rectangle rectangleForNewField, bool setReuseAppearance, bool isAppendMode, int certificationLevel, float?fontSize ) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); if (isAppendMode) { properties.UseAppendMode(); } PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), properties); signer.SetCertificationLevel(certificationLevel); PdfFont font = PdfFontFactory.CreateFont(FONT, "WinAnsi", true); // Creating the appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason(reason).SetLocation(location ).SetLayer2Font(font).SetReuseAppearance(setReuseAppearance); if (rectangleForNewField != null) { appearance.SetPageRect(rectangleForNewField); } if (fontSize != null) { appearance.SetLayer2FontSize((float)fontSize); } signer.SetFieldName(name); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public static void AssinaComCertificado(List <ICrlClient> crlList, string FileName, string SignFileName, CertSimples cert, int X, int Y, int Pagina, int Rotation, bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-256", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", TipoAssinatura Tipo = TipoAssinatura.Normal, string Cargo = "", string CREACRM = "") { string SourcePdfFileName = FileName; string DestPdfFileName = SignFileName; int Largura = 140; int Altura = 63; PdfReader pdfReader = new PdfReader(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); StampingProperties osp = new StampingProperties(); osp.UseAppendMode(); PdfSigner objStamper = new PdfSigner(pdfReader, signedPdf, osp); ITSAClient tsaClient = null; IOcspClient ocspClient = null; ConfiguraAparencia(objStamper, cert, X, Y, Largura, Altura, Pagina, Rotation, Contact, Reason, Location, Creator, Tipo); Org.BouncyCastle.X509.X509Certificate vert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(cert.Certificado); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] Arraychain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; X509CertificateParser objCP = new X509CertificateParser(); RSACryptoServiceProvider rsa; RSACryptoServiceProvider Provider; IExternalSignature externalSignature; if (cert.Certificado.PrivateKey is RSACryptoServiceProvider) { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } else { //RETIRAR ESSA PARTE PARA IMPLEMENTAR OS DEMAIS MÉTODOS, OLHANDO OUTROS TIPOS DE CERTIFICADO rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } if (AddTimeStamper) { tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass); } OCSPVerifier ocspVerifier = new OCSPVerifier(null, null); ocspClient = new OcspClientBouncyCastle(ocspVerifier); if (AplicaPolitica) { SignaturePolicyInfo spi = getPolitica(); objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES, spi); } else { objStamper.SignDetached(externalSignature, Arraychain, crlList, ocspClient, tsaClient, 0, PdfSigner.CryptoStandard.CADES); } try { signedPdf.Flush(); } catch { } try { signedPdf.Close(); } catch { }; pdfReader.Close(); }
private void TestSignatureOnRotatedPage(int pageNum, PdfSignatureAppearance.RenderingMode renderingMode, StringBuilder assertionResults) { String fileName = "signaturesOnRotatedPages" + pageNum + "_mode_" + renderingMode.ToString() + ".pdf"; String src = sourceFolder + "documentWithRotatedPages.pdf"; String dest = destinationFolder + fileName; PdfSigner signer = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), new StampingProperties ().UseAppendMode()); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetLayer2Text("Digitally signed by Test User. All rights reserved. Take care!").SetPageRect(new Rectangle(100, 100, 100, 50)).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create (sourceFolder + "itext.png")).SetPageNumber(pageNum); signer.SetCertificationLevel(PdfSigner.NOT_CERTIFIED); IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); // Make sure iText can open the document new PdfDocument(new PdfReader(dest)).Close(); try { String testResult = new CompareTool().CompareVisually(dest, sourceFolder + "cmp_" + fileName, destinationFolder , "diff_"); if (null != testResult) { assertionResults.Append(testResult); } } catch (CompareTool.CompareToolExecutionException e) { assertionResults.Append(e.Message); } }
public void testSignSimpleDsaSha256() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; char[] storePass = "******".ToCharArray(); string storeAlias = "DSAkey"; Pkcs12Store pkcs12 = new Pkcs12Store(new FileStream(storePath, FileMode.Open, FileAccess.Read), storePass); AsymmetricKeyParameter key = pkcs12.GetKey(storeAlias).Key; X509CertificateEntry[] chainEntries = pkcs12.GetCertificateChain(storeAlias); X509Certificate[] chain = new X509Certificate[chainEntries.Length]; for (int i = 0; i < chainEntries.Length; i++) { chain[i] = chainEntries[i].Certificate; } PrivateKeySignatureContainer signature = new PrivateKeySignatureContainer(key, chain, "SHA256withDSA"); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-DSASHA256-BC-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); pdfSigner.SignExternalContainer(signature, 8192); } }
public void testSignSimpleECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; string storePass = "******"; string storeAlias = "ECDSAkey"; SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection(); pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet); SystemCertificates.X509Certificate2 certificate = null; foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12) { if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase)) { certificate = aCertificate; break; } } Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias); X509Certificate bcCertificate = new X509Certificate(X509CertificateStructure.GetInstance(certificate.RawData)); X509Certificate[] chain = { bcCertificate }; X509Certificate2Signature signature = new X509Certificate2Signature(certificate, "SHA512"); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); ITSAClient tsaClient = null; pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS); } }
private byte[] Sign(byte[] src, Org.BouncyCastle.X509.X509Certificate[] chain, ICipherParameters pk, string digestAlgorithm, PdfSigner.CryptoStandard subfilter, string signatureFieldName ) { using (MemoryStream outputMemoryStream = new MemoryStream()) using (MemoryStream memoryStream = new MemoryStream(src)) using (PdfReader pdfReader = new PdfReader(memoryStream)) { PdfSigner signer = new PdfSigner( pdfReader, outputMemoryStream, new StampingProperties().UseAppendMode() ); signer.SetFieldName(signatureFieldName); IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); try { // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(pks, chain, null, null, null, 0, subfilter); } catch (Exception ex) { throw; } pdfReader.Close(); memoryStream.Close(); var documentoAssinado = outputMemoryStream.ToArray(); outputMemoryStream.Close(); return(documentoAssinado); } }
public void Sign2(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(reason); appearance.SetLocation(location); signer.SetFieldName(name); // Creating the appearance for layer 2 PdfFormXObject n2 = appearance.GetLayer2(); // Custom text, custom font, and right-to-left writing // Characters: لورانس العرب Text text = new Text("\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628"); text.SetFont(PdfFontFactory.CreateFont("../../../resources/font/NotoNaskhArabic-Regular.ttf", PdfEncodings.IDENTITY_H, true)); text.SetBaseDirection(BaseDirection.RIGHT_TO_LEFT); new Canvas(n2, signer.GetDocument()).Add(new Paragraph(text).SetTextAlignment(TextAlignment.RIGHT)); IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public void testSignSimpleContainerECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; string storePass = "******"; string storeAlias = "ECDSAkey"; SystemCertificates.X509Certificate2Collection pkcs12 = new SystemCertificates.X509Certificate2Collection(); pkcs12.Import(storePath, storePass, SystemCertificates.X509KeyStorageFlags.DefaultKeySet); SystemCertificates.X509Certificate2 certificate = null; foreach (SystemCertificates.X509Certificate2 aCertificate in pkcs12) { if (storeAlias.Equals(aCertificate.FriendlyName, StringComparison.InvariantCultureIgnoreCase)) { certificate = aCertificate; break; } } Assert.NotNull(certificate, "Key with alias {0} not found.", storeAlias); X509Certificate2SignatureContainer signature = new X509Certificate2SignatureContainer(certificate, signer => { signer.DigestAlgorithm = Oid.FromFriendlyName("SHA512", OidGroup.HashAlgorithm); }); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-signed-simple-container.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); pdfSigner.SignExternalContainer(signature, 8192); } }
public void Sign1(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, String reason, String location) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); // Create the signature appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance .SetReason(reason) .SetLocation(location); // This name corresponds to the name of the field that already exists in the document. signer.SetFieldName(name); // Set the custom text and a custom font appearance.SetLayer2Text("This document was signed by Bruno Specimen"); appearance.SetLayer2Font(PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN)); IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String dest, X509Certificate[] chain, PdfSigner.CryptoStandard subfilter, String reason, String location) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); // Create the signature appearance //Rectangle rect = new Rectangle(36, 648, 200, 100); //iText.Signatures.PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); //appearance // .SetReason(reason) // .SetLocation(location) // .SetPageRect(rect) // .SetPageNumber(1); signer.SetFieldName("QAMgr"); //IExternalDigest digest = new BouncyCastleDigest(); IExternalSignature signature = new ServerSignature(); //IExternalSignature sing = new // Sign the document using the detached mode, CMS or CAdES equivalent. //signer.SignDetached(digest, signature, chain, null, null, null, // 0, subfilter); // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(signature, chain, null, null, null, 0, subfilter); }
public void Sign(String src, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, int certificationLevel, String reason, String location) { PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties()); // Create the signature appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(reason); appearance.SetLocation(location); Rectangle rect = new Rectangle(36, 648, 200, 100); appearance.SetPageRect(rect).SetPageNumber(1); signer.SetFieldName("sig"); /* Set the document's certification level. This parameter defines if changes are allowed * after the applying of the signature. */ signer.SetCertificationLevel(certificationLevel); PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm); // Sign the document using the detached mode, CMS or CAdES equivalent. signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public virtual void LtvEnabledTest01() { String tsaCertFileName = certsSrc + "tsCertRsa.p12"; String caCertFileName = certsSrc + "rootRsa.p12"; String srcFileName = sourceFolder + "signedDoc.pdf"; String ltvFileName = destinationFolder + "ltvEnabledTest01.pdf"; String ltvTsFileName = destinationFolder + "ltvEnabledTsTest01.pdf"; X509Certificate[] tsaChain = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password); ICipherParameters tsaPrivateKey = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password); X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0]; ICipherParameters caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); TestOcspClient testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, caPrivateKey); TestCrlClient testCrlClient = new TestCrlClient(caCert, caPrivateKey); PdfDocument document = new PdfDocument(new PdfReader(srcFileName), new PdfWriter(ltvFileName), new StampingProperties ().UseAppendMode()); LtvVerification ltvVerification = new LtvVerification(document); ltvVerification.AddVerification("Signature1", testOcspClient, testCrlClient, LtvVerification.CertificateOption .SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES); ltvVerification.Merge(); document.Close(); PdfSigner signer = new PdfSigner(new PdfReader(ltvFileName), new FileStream(ltvTsFileName, FileMode.Create ), new StampingProperties().UseAppendMode()); signer.Timestamp(testTsa, "timestampSig1"); BasicCheckLtvDoc("ltvEnabledTsTest01.pdf", "timestampSig1"); }
public static async Task SignPdfFileAsync(String accessToken, String credentialId, String pin, String otp, String inPath, String outPath) { try { PdfReader reader = new PdfReader(inPath); PdfSigner signer = new PdfSigner(reader, new FileStream(outPath, FileMode.Create), false); PdfSignatureAppearance appearance = signer.GetSignatureAppearance() .SetReason("Reason") .SetLocation("Romania") .SetReuseAppearance(false); Rectangle rect = new Rectangle(36, 648, 200, 100); appearance.SetPageRect(rect).SetPageNumber(1); signer.SetFieldName("sig"); IExternalSignature pks = new CSCPAdESSignature(accessToken, credentialId, pin, otp); X509Certificate [] chain = await CSC_API_Utils.GetCertChainAsync(accessToken, credentialId); ICrlClient signingCertCrl = new CrlClientOnline(chain); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(signingCertCrl); signer.SignDetached(pks, chain, crlList, null, null, 0, PdfSigner.CryptoStandard.CADES); } catch (Exception e) { } }
public void Sign(String keystore, String src, String name, String dest) { Pkcs12Store pk12 = new Pkcs12Store(new FileStream(keystore, FileMode.Open, FileAccess.Read), PASSWORD); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } PdfReader reader = new PdfReader(src); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), new StampingProperties().UseAppendMode()); signer.SetFieldName(name); PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS); }
public static async Task SignPdfFile(String accessToken, String credentialId, String pin, String otp, String inPath, String outPath) { try { PdfReader reader = new PdfReader(inPath); PdfSigner signer = new PdfSigner(reader, new FileStream(outPath, FileMode.Create), new StampingProperties()); PdfSignatureAppearance appearance = signer.GetSignatureAppearance() .SetReason("Test semnatura digitala") .SetLocation("Bucuresti, RO") .SetReuseAppearance(false); Rectangle rect = new Rectangle(300, 690, 200, 100); appearance.SetPageRect(rect).SetPageNumber(1); signer.SetFieldName("semnatura iText7"); IExternalSignature pks = new CSCPAdESSignature(accessToken, credentialId, pin, otp); X509Certificate[] chain = await CSC_API_Utils.GetCertChainAsync(accessToken, credentialId); ICrlClient signingCertCrl = new CrlClientOnline(chain); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(signingCertCrl); ITSAClient tsaClient = new TSAClientBouncyCastle("http://timestamp.globalsign.com/scripts/timestamp.dll"); signer.SignDetached(pks, chain, crlList, null, tsaClient, 0, PdfSigner.CryptoStandard.CADES); } catch (Exception e) { logger.Error(e.Message); } }
public virtual void SignEncryptedDoc01() { String fileName = "encrypted.pdf"; String src = sourceFolder + fileName; String dest = destinationFolder + "signed_" + fileName; String fieldName = "Signature1"; byte[] ownerPass = "******".GetBytes(); PdfReader reader = new PdfReader(src, new ReaderProperties().SetPassword(ownerPass)); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), true); // Creating the appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance().SetReason("Test1").SetLocation("TestCity" ); signer.SetFieldName(fieldName); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); LtvVerifier verifier = new LtvVerifier(new PdfDocument(new PdfReader(dest, new ReaderProperties().SetPassword (ownerPass)))); verifier.SetVerifyRootCertificate(false); verifier.Verify(null); }
public static void Sign(IExternalSignature externalSignature, X509Certificate2 rawCertificate, string sourcePdfPath, string destinationPdfPath) { if (externalSignature == null) { throw new ArgumentNullException(nameof(externalSignature)); } if (rawCertificate == null) { throw new ArgumentNullException(nameof(rawCertificate)); } if (sourcePdfPath == null) { throw new ArgumentNullException(nameof(sourcePdfPath)); } if (destinationPdfPath == null) { throw new ArgumentNullException(nameof(destinationPdfPath)); } using PdfReader reader = new PdfReader(sourcePdfPath); Org.BouncyCastle.X509.X509Certificate bCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(rawCertificate); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { bCert }; using FileStream stream = new FileStream(destinationPdfPath, FileMode.OpenOrCreate); PdfSigner signer = new PdfSigner(reader, stream, new StampingProperties()); signer.SetSignatureEvent(new SignatureEvent()); signer.SignDetached(externalSignature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); }
public virtual void LtvEnabledSingleSignatureTest01() { String signCertFileName = certsSrc + "signCertRsaWithChain.p12"; String tsaCertFileName = certsSrc + "tsCertRsa.p12"; String intermediateCertFileName = certsSrc + "intermediateRsa.p12"; String caCertFileName = certsSrc + "rootRsa.p12"; String srcFileName = sourceFolder + "helloWorldDoc.pdf"; String ltvFileName = destinationFolder + "ltvEnabledSingleSignatureTest01.pdf"; X509Certificate[] tsaChain = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password); ICipherParameters tsaPrivateKey = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password); X509Certificate intermediateCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(intermediateCertFileName , password)[0]; ICipherParameters intermediatePrivateKey = Pkcs12FileHelper.ReadFirstKey(intermediateCertFileName, password , password); X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0]; ICipherParameters caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password); TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey); TestOcspClient testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(intermediateCert, intermediatePrivateKey ).AddBuilderForCertIssuer(caCert, caPrivateKey); X509Certificate[] signChain = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password); ICipherParameters signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password); IExternalSignature pks = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256); PdfSigner signer = new PdfSigner(new PdfReader(srcFileName), new FileStream(ltvFileName, FileMode.Create), new StampingProperties()); signer.SetFieldName("Signature1"); signer.SignDetached(pks, signChain, null, testOcspClient, testTsa, 0, PdfSigner.CryptoStandard.CADES); PadesSigTest.BasicCheckSignedDoc(destinationFolder + "ltvEnabledSingleSignatureTest01.pdf", "Signature1"); }
public static void Sign(string fileName, string signedFileName, string reason, string location, string privateKeyFileName, string certFileName, string password) { PdfReader reader = new PdfReader(fileName); PdfWriter write = new PdfWriter(signedFileName); PdfSigner signer = new PdfSigner(reader, write, false); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(reason); appearance.SetLocation(location); appearance.SetReuseAppearance(false); Rectangle rect = new Rectangle(36, 648, 200, 100); appearance.SetPageRect(rect); appearance.SetPageNumber(1); signer.SetFieldName("sig"); IExternalSignature pks = new PrivateKeySignature(ReadPrivateKey(privateKeyFileName, password), GetEncryptionAlgorithm()); X509CertificateParser parser = new X509CertificateParser(); X509Certificate cert = LoadCertificate(certFileName); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; PdfSigner.CryptoStandard subfilter = GetSubFilter(); signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public void testSignSimpleECDsa() { string testFileName = @"..\..\..\resources\circles.pdf"; string storePath = @"..\..\..\..\simple\keystore\test1234.p12"; char[] storePass = "******".ToCharArray(); string storeAlias = "ECDSAkey"; Pkcs12Store pkcs12 = new Pkcs12Store(new FileStream(storePath, FileMode.Open, FileAccess.Read), storePass); AsymmetricKeyParameter key = pkcs12.GetKey(storeAlias).Key; X509CertificateEntry[] chainEntries = pkcs12.GetCertificateChain(storeAlias); X509Certificate[] chain = new X509Certificate[chainEntries.Length]; for (int i = 0; i < chainEntries.Length; i++) { chain[i] = chainEntries[i].Certificate; } PrivateKeySignature signature = new PrivateKeySignature(key, "SHA512"); using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-ECDSA-BC-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); ITSAClient tsaClient = null; pdfSigner.SignDetached(signature, chain, null, null, tsaClient, 0, PdfSigner.CryptoStandard.CMS); } }
private void BuildSignatureAppearance(PdfSigner signer, Signature signing) { // Creating the appearance PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(signing.SignReason); appearance.SetContact(signing.SignContact); appearance.SetLocation(signing.SignLocation); var arial = PdfFontFactory.CreateFont(Environment.GetEnvironmentVariable("WINDIR") + "\\Fonts\\Arial.ttf", PdfName.WinAnsiEncoding.GetValue(), true); appearance.SetLayer2Font(arial); if (!signing.AllowMultiSigning) { signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS); appearance.SetCertificate(signer.GetSignatureAppearance().GetCertificate()); } if (signing.DisplaySignatureInDocument) { var signPage = SignPageNr(signer, signing); var left = signing.LeftX; var bottom = signing.LeftY; var width = signing.RightX - left; var height = signing.RightY - bottom; var rect = new Rectangle(left, bottom, width, height); appearance.SetPageRect(rect); appearance.SetPageNumber(signPage); } }
private void AdicionarLtv(string pdfPrimeiraAssinatura, SingInfo singInfo) { var inicioCarimbo = DateTime.Now; var stamping = new StampingProperties(); stamping.UseAppendMode(); PdfDocument pdfDoc = new PdfDocument( new PdfReader(pdfPrimeiraAssinatura), new PdfWriter(singInfo.TargetPdf)); LtvVerification v = new LtvVerification(pdfDoc); SignatureUtil signatureUtil = new SignatureUtil(pdfDoc); var names = signatureUtil.GetSignatureNames(); var sigName = names[names.Count - 1]; var pkcs7 = signatureUtil.VerifySignature(sigName); if (pkcs7.IsTsp()) { v.AddVerification( sigName, this.ocspClient, new CrlClientOnline(this.cadeiaTempo.ToArray()), LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES); } else { foreach (var name in names) { v.AddVerification( name, this.ocspClient, new CrlClientOnline(this.cadeiaTempo.ToArray()), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO); } } pdfDoc.Close(); Console.WriteLine("Aplicando timestamp........"); PdfReader r = new PdfReader(pdfPrimeiraAssinatura); PdfSigner pdfSigner = new PdfSigner(r, new FileStream(singInfo.TargetPdf, FileMode.Create), stamping); pdfSigner.Timestamp(this.tsaClient, null); var fimCarimbo = DateTime.Now; var tempoCarimbo = fimCarimbo.Subtract(inicioCarimbo); Console.WriteLine("Tempo Carimbo: {0}ms", tempoCarimbo.TotalMilliseconds); }
public static void SignPdf(string certificate, string signature) { byte[] signatureBytes = ConvertToBytes(signature); byte[] certificateBytes = ConvertToBytes(certificate); var acsd = Encoding.Default.GetString(signatureBytes); var chains = GetChains(); var datasplited = chain.Split("="); var a = HttpUtility.UrlDecode(datasplited[1]); var b = a.Split(";"); Console.WriteLine(a); X509Certificate x509Certificate = new X509CertificateParser().ReadCertificate(certificateBytes); SignerIdentifier sid = new SignerIdentifier(new IssuerAndSerialNumber(x509Certificate.IssuerDN, x509Certificate.SerialNumber)); AlgorithmIdentifier digAlgorithm = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256); Attributes authenticatedAttributes = null; AlgorithmIdentifier digEncryptionAlgorithm = new AlgorithmIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Sha256WithRsaEncryption); Asn1OctetString encryptedDigest = new DerOctetString(signatureBytes); Attributes unauthenticatedAttributes = null; SignerInfo signerInfo = new SignerInfo(sid, digAlgorithm, authenticatedAttributes, digEncryptionAlgorithm, encryptedDigest, unauthenticatedAttributes); Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); digestAlgs.Add(signerInfo.DigestAlgorithm); Asn1Set digestAlgorithms = new DerSet(digestAlgs); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.Data, null); Asn1EncodableVector certs = new Asn1EncodableVector(); certs.Add(x509Certificate.CertificateStructure.ToAsn1Object()); for (int i = 0; i < chains.Length; i++) { certs.Add(chains[i].CertificateStructure.ToAsn1Object()); } Asn1Set certificates = new DerSet(certs); Asn1EncodableVector signerInfs = new Asn1EncodableVector(); signerInfs.Add(signerInfo); Asn1Set signerInfos = new DerSet(signerInfs); SignedData signedData = new SignedData(digestAlgorithms, contentInfo, certificates, null, signerInfos); contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, signedData); byte[] Signature = contentInfo.GetDerEncoded(); using (PdfReader reader = new PdfReader(temp)) using (PdfDocument document = new PdfDocument(reader)) using (FileStream fout = new FileStream(dest, FileMode.Create)) { PdfSigner.SignDeferred(document, "Signature", fout, new ExternalPrecalculatedSignatureContainer(Signature)); } }
public static void Sign(string input, string output, ImageData stamper, ICipherParameters privateKey, X509Certificate[] chain, string flag) { PdfDocument document = new PdfDocument(new PdfReader(input)); PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false); bool append = (acroForm != null && acroForm.GetSignatureFlags() != 0); int pageNumber = document.GetNumberOfPages(); RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(flag); PdfDocumentContentParser parser = new PdfDocumentContentParser(document); parser.ProcessContent(pageNumber, strategy); var locations = new List <IPdfTextLocation>(strategy.GetResultantLocations()); document.Close(); StampingProperties properties = new StampingProperties(); properties = append ? properties.UseAppendMode() : properties; PdfSigner signer = new PdfSigner(new PdfReader(input), new FileStream(output, FileMode.Create), properties); signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetPageNumber(pageNumber); int size = locations.Count; if (size != 0) { IPdfTextLocation location = locations[size - 1]; float flagX = location.GetRectangle().GetX(); float flagY = location.GetRectangle().GetY(); float width = stamper.GetWidth(); float height = stamper.GetHeight(); float x = flagX - width / 2; float y = flagY - height / 2; appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); appearance.SetSignatureGraphic(stamper); appearance.SetPageRect(new Rectangle(x, y, width, height)); } PrivateKeySignature signature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); signer.SignDetached(signature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); }
static void Main(string[] args) { Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(options => { string keystore = options.SignatureCertificate; char[] password = options.SignaturePassword.ToCharArray(); Pkcs12Store pkcs12Store = new Pkcs12Store(new FileStream(keystore, FileMode.Open, FileAccess.Read), password); string keyAlias = null; foreach (object alias in pkcs12Store.Aliases) { keyAlias = (string)alias; if (pkcs12Store.IsKeyEntry(keyAlias)) { break; } } ICipherParameters key = pkcs12Store.GetKey(keyAlias).Key; X509CertificateEntry[] certificateEntry = pkcs12Store.GetCertificateChain(keyAlias); X509Certificate[] certificate = new X509Certificate[certificateEntry.Length]; for (int i = 0; i < certificateEntry.Length; ++i) { certificate[i] = certificateEntry[i].Certificate; } string srcPdf = options.SrcPdf; string destPdf = System.IO.Path.GetTempFileName(); PdfReader pdfReader = new PdfReader(srcPdf); PdfSigner pdfSigner = new PdfSigner(pdfReader, new FileStream(destPdf, FileMode.Create), new StampingProperties()); PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance(); appearance .SetLayer2Text(options.SignatureText) .SetPageRect(new Rectangle(options.SignatureRectangleX, options.SignatureRectangleY, options.SignatureRectangleWidth, options.SignatureRectangleHeight)) .SetPageNumber(1); pdfSigner.SetFieldName(options.SignatureName); IExternalSignature privateKeySignature = new PrivateKeySignature(key, DigestAlgorithms.SHA256); pdfSigner.SignDetached(privateKeySignature, certificate, null, null, null, 0, PdfSigner.CryptoStandard.CMS); Console.WriteLine(destPdf); }); }