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(); }
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 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 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 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 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) { } }
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 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 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 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 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 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); } }
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); }
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 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); } }
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 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); }
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); }); }
public void TestPkcs11SignSimple() { string testFileName = @"..\..\..\resources\circles.pdf"; using (Pkcs11Signature signature = new Pkcs11Signature(@"d:\Program Files\SoftHSM2\lib\softhsm2-x64.dll", 171137967).Select(null, "5678").SetHashAlgorithm("SHA256")) using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-pkcs11-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); pdfSigner.SignDetached(signature, signature.GetChain(), null, null, null, 0, CryptoStandard.CMS); } }
private static void _gerarPdfAssinado(AssinarDTO dadosAssinatura, string SRC, string DEST, ICipherParameters pk, X509Certificate[] chain) { using (FileStream fileStramDestino = new FileStream(DEST, FileMode.Create)) using (PdfReader reader = new PdfReader(SRC)) { PdfSigner signer = new PdfSigner(reader, fileStramDestino, new StampingProperties()); _addCarimbo(dadosAssinatura, chain, signer); //finalizando IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS); } }
private static void SignPdf(X509Certificate2 certificate, IExternalSignature externalSignature, string signedPdfName) { var bCert = DotNetUtilities.FromX509Certificate(certificate); var chain = new Org.BouncyCastle.X509.X509Certificate[] { bCert }; using (var reader = new PdfReader("Hello World.pdf")) { using (var stream = new FileStream(signedPdfName, FileMode.OpenOrCreate)) { var signer = new PdfSigner(reader, stream, false); signer.SignDetached(externalSignature, chain, null, null, null, 0, PdfSigner.CryptoStandard.CMS); } } }
public void TestPkcs11SignSimple() { string testFileName = @"..\..\..\resources\circles.pdf"; using (Pkcs11Signature signature = new Pkcs11Signature(@"PKCS11LIBRARY", 1).Select("KEYALIAS", "CERTLABEL", "1234").SetHashAlgorithm("SHA256")) using (PdfReader pdfReader = new PdfReader(testFileName)) using (FileStream result = File.Create("circles-pkcs11-signed-simple.pdf")) { PdfSigner pdfSigner = new PdfSigner(pdfReader, result, new StampingProperties().UseAppendMode()); ITSAClient tsaClient = null; pdfSigner.SignDetached(signature, signature.GetChain(), null, null, tsaClient, 0, CryptoStandard.CMS); } }
private void SignApproval(String signCertFileName, String outFileName, SignaturePolicyIdentifier sigPolicyInfo ) { String srcFileName = sourceFolder + "helloWorldDoc.pdf"; 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(outFileName, FileMode.Create), new StampingProperties()); signer.SetFieldName("Signature1"); signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText7."); if (sigPolicyInfo == null) { signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); } else { signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES, sigPolicyInfo); } }
public async Task <byte[]> Sign(byte[] source, SigningProperties signingProperties) { using (var inputStream = new MemoryStream(source)) using (var reader = new PdfReader(inputStream)) using (var outputStream = new MemoryStream()) { var stampProps = new StampingProperties(); var signer = new PdfSigner(reader, outputStream, stampProps); signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); var sap = signer.GetSignatureAppearance(); sap.SetLocation(signingProperties.Location); sap.SetReason(signingProperties.Reason); sap.SetReuseAppearance(false); var certData = await s3Repository.GetDocument(signingProperties.Bucket, signingProperties.Key); // code from https://stackoverflow.com/questions/12470498/how-to-read-the-pfx-file using (var keyStream = new MemoryStream(certData)) { var passphrase = signingProperties.Password; if (signingProperties.KMSData != null) { // key is encrypted with KSM var key = await kSMRepository.GetKey(signingProperties.KMSData); passphrase = kSMRepository.DecryptData(passphrase, key); } var store = new Pkcs12Store(keyStream, signingProperties.Password.ToCharArray()); string alias = store.Aliases.OfType <string>().First(x => store.IsKeyEntry(x)); var privateKey = store.GetKey(alias).Key; var keyChain = store.GetCertificateChain(alias) .Select(x => x.Certificate).ToArray(); IExternalSignature externalSignature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); signer.SignDetached(externalSignature, keyChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); return(outputStream.ToArray()); } } }
protected internal virtual void Sign(String src, String name, String dest, X509Certificate[] chain, ICipherParameters pk, String digestAlgorithm, PdfSigner.CryptoStandard subfilter, int certificationLevel) { PdfReader reader = new PdfReader(src); StampingProperties properties = new StampingProperties(); properties.UseAppendMode(); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), properties); signer.SetCertificationLevel(certificationLevel); signer.SetFieldName(name); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); signer.SignDetached(pks, chain, null, null, null, 0, subfilter); }
public virtual void SignEncryptedDoc02() { String fileName = "encrypted_cert.pdf"; String src = sourceFolder + fileName; String dest = destinationFolder + "signed_" + fileName; X509Certificate cert = CryptoUtil.ReadPublicCertificate(new FileStream(sourceFolder + "test.cer", FileMode.Open , FileAccess.Read)); ICipherParameters privateKey = Pkcs12FileHelper.ReadFirstKey(sourceFolder + "test.p12", password, password ); PdfReader reader = new PdfReader(src, new ReaderProperties().SetPublicKeySecurityParams(cert, privateKey)); PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), true); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/> private void TestSignatureAppearanceAutoscale(String dest, Rectangle rect, PdfSignatureAppearance.RenderingMode renderingMode) { String src = sourceFolder + "simpleDocument.pdf"; PdfSigner signer = new PdfSigner(new PdfReader(src), new FileStream(dest, FileMode.Create), false); // Creating the appearance signer.GetSignatureAppearance().SetLayer2FontSize(0).SetReason("Test 1").SetLocation("TestCity").SetPageRect (rect).SetRenderingMode(renderingMode).SetSignatureGraphic(ImageDataFactory.Create(sourceFolder + "itext.png" )); signer.SetFieldName("Signature1"); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); }