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(); }
/// <summary> /// PDF imzalar. /// </summary> /// <param name="request"></param> /// <param name="PDFContent"></param> /// <returns></returns> public byte[] SignPDF(PdfRequestDTO request , byte[] PDFContent ) { //if (PDFContent == null || request == null) //{ // return null; //} X509Certificate2 signingCertificate; IExternalSignature externalSignature; this.SelectSignature(request, out signingCertificate, out externalSignature); X509Certificate2[] chain = generateCertificateChain(signingCertificate); ICollection <X509Certificate> Bouncychain = chainToBouncyCastle(chain); ocsp = new OcspClientBouncyCastle(); crl = new ITextSharp.iTextSharp.text.pdf.security.CrlClientOnline(Bouncychain); PdfReader pdfReader = new PdfReader(PDFContent); MemoryStream stream = new MemoryStream(); PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, stream, '\0', "", true); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; crlList = new List <ICrlClient>(); crlList.Add(crl); lock (lockSign) { ITextSharp.iTextSharp.text.pdf.security.MakeSignature.SignDetached(signatureAppearance, externalSignature, Bouncychain, crlList, ocsp, null, 0, CryptoStandard.CMS); } return(stream.ToArray()); }
public static void Smartcardsign(Session session, String alias) { // Searchs for an RSA certificate object // Sets the template with its attributes CryptokiCollection template = new CryptokiCollection(); template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_CERTIFICATE)); template.Add(new ObjectAttribute(ObjectAttribute.CKA_CERTIFICATE_TYPE, Certificate.CKC_X_509)); template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias)); Cryptware.NCryptoki.X509Certificate nCert = (Cryptware.NCryptoki.X509Certificate)session.Objects.Find(template); X509Certificate2 cert = Utils.ConvertCertificate(nCert); ICollection <X509Certificate> chain = new List <X509Certificate>(); X509Chain x509chain = new X509Chain(); x509chain.Build(cert); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } IOcspClient ocspClient = new OcspClientBouncyCastle(); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); C4_03_SignWithPKCS11SC app = new C4_03_SignWithPKCS11SC(); app.Sign(SRC, String.Format(DEST, alias), chain, session, alias, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, ocspClient, null, 0); }
public static void Main(String[] args) { Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } IOcspClient ocspClient = new OcspClientBouncyCastle(); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, null, 0); }
public static void Main(String[] args) { Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String path = properties["PRIVATE"]; char[] pass = properties["PASSWORD"].ToCharArray(); String tsaUrl = properties["TSAURL"]; String tsaUser = properties["TSAUSERNAME"]; String tsaPass = properties["TSAPASSWORD"]; Pkcs12Store ks = new Pkcs12Store(); ks.Load(new FileStream(path, FileMode.Open), pass); String alias = ""; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyParameter pk = ks.GetKey(alias).Key; IList <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) { chain.Add(entry.Certificate); } IOcspClient ocspClient = new OcspClientBouncyCastle(); TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass); C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize(); bool succeeded = false; int estimatedSize = 10300; while (!succeeded) { try { Console.WriteLine("Attempt: " + estimatedSize + " bytes"); C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, tsaClient, estimatedSize); succeeded = true; Console.WriteLine("Succeeded!"); } catch (IOException ioe) { Console.WriteLine("Not succeeded: " + ioe.Message); estimatedSize += 50; } } Console.ReadKey(); }
public static string SignFile(string fileName, PdfSignatureParameters parameters, IDigitalSignatureCertificateSelector certificateSelector) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Filename must be given", nameof(fileName)); } if (!File.Exists(fileName)) { throw new ArgumentException($"File {fileName} not found."); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (certificateSelector == null) { throw new ArgumentNullException(nameof(certificateSelector)); } string tempPath = string.Empty; try { tempPath = GetTempPath(parameters.TempFolderPath); string targetFilePath = GetTargetFilePath(parameters.TempFolderPath, parameters.TargetFilePath); var signingCertificates = CertificateHelper.GetSigningCertificates(certificateSelector); // Two clients for checking certificate revocation // * Online Certificate Status Protocol (OCSP) client // * Certificate Revocation Lists (CRL) client with online checking // Certificate will be checked when the signature is made OcspClientBouncyCastle oscpClient = new OcspClientBouncyCastle(null); List<ICrlClient> clrClients = new List<ICrlClient> { new CrlClientOnline(signingCertificates.FinalChain) }; using (FileStream targetFileStream = new FileStream(targetFilePath, FileMode.Create)) using (PdfReader reader = new PdfReader(fileName)) { PdfStamper stamper = PdfStamper.CreateSignature(reader, targetFileStream, '0', tempPath, true); PdfSignatureAppearance appearance = GetPdfSignatureAppearance(signingCertificates, stamper, reader, parameters); CreateSignature(signingCertificates, appearance, clrClients, oscpClient); } return targetFilePath; } finally { if (!string.IsNullOrWhiteSpace(tempPath) && File.Exists(tempPath)) { File.Delete(tempPath); } } }
public static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); X509Store x509Store = new X509Store("My"); x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = x509Store.Certificates; IList <X509Certificate> chain = new List <X509Certificate>(); X509Certificate2 pk = null; if (certificates.Count > 0) { X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator(); certificatesEn.MoveNext(); pk = certificatesEn.Current; X509Chain x509chain = new X509Chain(); x509chain.Build(pk); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } } x509Store.Close(); IOcspClient ocspClient = new OcspClientBouncyCastle(); ITSAClient tsaClient = null; for (int i = 0; i < chain.Count; i++) { X509Certificate cert = chain[i]; String tsaUrl = CertificateUtil.GetTSAURL(cert); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); break; } } IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); C3_11_SignWithToken app = new C3_11_SignWithToken(); app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, ocspClient, tsaClient, 0); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); String tsaUrl = properties.GetProperty("TSAURL"); String tsaUser = properties.GetProperty("TSAUSERNAME"); String tsaPass = properties.GetProperty("TSAPASSWORD"); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); 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; } IOcspClient ocspClient = new OcspClientBouncyCastle(null); /* Create an instance of TSAClientBouncyCastle, an implementation of TSAClient. * Pass the timestamp authority server url. * Note that not all TSA would require user credentials. */ ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass); new C3_09_SignWithTSA().Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, tsaClient, 0); }
static byte[] GetCertificateChainOCSP(X509Certificate[] certificateChain) { byte[] ocsp = null; if (certificateChain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(certificateChain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle(certificateChain[0], certificateChain[1], url).GetEncoded(); } } return(ocsp); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); 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; } /* Create an instance of OcspClientBouncyCastle, an implementation of OcspClient. * In the current sample it is not needed to verify the OCSP response, * that is why null is passed as verifier parameter. */ IOcspClient ocspClient = new OcspClientBouncyCastle(null); new C3_07_SignWithOCSP().Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, null, 0); }
public static void GetCertificateProperties(string thumbprint, out IList <X509Certificate> chain, out X509Certificate2 pk, out IOcspClient ocspClient, out ITSAClient tsaClient, out IList <ICrlClient> crlList) { GetPK(thumbprint, out chain, out pk); ocspClient = new OcspClientBouncyCastle(); tsaClient = null; for (int i = 0; i < chain.Count; i++) { X509Certificate cert = chain[i]; String tsaUrl = CertificateUtil.GetTSAURL(cert); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); break; } } crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); }
public static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); X509Store x509Store = new X509Store("My"); x509Store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = x509Store.Certificates; IList<X509Certificate> chain = new List<X509Certificate>(); X509Certificate2 pk = null; if (certificates.Count > 0) { X509Certificate2Enumerator certificatesEn = certificates.GetEnumerator(); certificatesEn.MoveNext(); pk = certificatesEn.Current; X509Chain x509chain = new X509Chain(); x509chain.Build(pk); foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) { chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate)); } } x509Store.Close(); IOcspClient ocspClient = new OcspClientBouncyCastle(); ITSAClient tsaClient = null; for (int i = 0; i < chain.Count; i++) { X509Certificate cert = chain[i]; String tsaUrl = CertificateUtil.GetTSAURL(cert); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); break; } } IList<ICrlClient> crlList = new List<ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); C3_11_SignWithToken app = new C3_11_SignWithToken(); app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent", crlList, ocspClient, tsaClient, 0); }
public static void Main(String[] args) { LoggerFactory.GetInstance().SetLogger(new SysoLogger()); Properties properties = new Properties(); properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open)); String tsaUrl = properties["TSAURL"]; String tsaUser = properties["TSAUSERNAME"]; String tsaPass = properties["TSAPASSWORD"]; C5_04_LTV app = new C5_04_LTV(); ITSAClient tsa = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass, 6500, "SHA512"); IOcspClient ocsp = new OcspClientBouncyCastle(); app.AddLtv(EXAMPLE1, String.Format(DEST, 1), ocsp, new CrlClientOnline(), tsa); Console.WriteLine(); app.AddLtv(EXAMPLE2, String.Format(DEST, 2), ocsp, new CrlClientOnline(), tsa); Console.WriteLine(); app.AddLtv(EXAMPLE3, String.Format(DEST, 3), ocsp, new CrlClientOnline(), tsa); Console.WriteLine(); app.AddLtv(String.Format(DEST, 1), String.Format(DEST, 4), null, new CrlClientOnline(), tsa); }
protected void SignDocumentSignature(string filePath, ElectronicSignatureInfoDTO signatureInfo) { PdfSigner pdfSigner = new PdfSigner(new PdfReader(SRC), new FileStream(filePath, FileMode.Create), new StampingProperties()); pdfSigner.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); // Set the name indicating the field to be signed. // The field can already be present in the document but shall not be signed pdfSigner.SetFieldName("signature"); ImageData clientSignatureImage = ImageDataFactory.Create(IMAGE_PATH); // If you create new signature field (or use SetFieldName(System.String) with // the name that doesn't exist in the document or don't specify it at all) then // the signature is invisible by default. PdfSignatureAppearance signatureAppearance = pdfSigner.GetSignatureAppearance(); signatureAppearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); signatureAppearance.SetReason(""); signatureAppearance.SetLocationCaption(""); signatureAppearance.SetSignatureGraphic(clientSignatureImage); signatureAppearance.SetPageNumber(signatureInfo.PageNumber); signatureAppearance.SetPageRect(new Rectangle(signatureInfo.Left, signatureInfo.Bottom, 25, 25)); char[] password = "******".ToCharArray(); IExternalSignature pks = GetPrivateKeySignature(CERT_PATH, password); X509Certificate[] chain = GetCertificateChain(CERT_PATH, password); OCSPVerifier ocspVerifier = new OCSPVerifier(null, null); OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(ocspVerifier); List <ICrlClient> crlClients = new List <ICrlClient>(new[] { new CrlClientOnline() }); // Sign the document using the detached mode, CMS or CAdES equivalent. // This method closes the underlying pdf document, so the instance // of PdfSigner cannot be used after this method call pdfSigner.SignDetached(pks, chain, crlClients, ocspClient, null, 0, PdfSigner.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 Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption enc) { byte[] ownerPassword = null; if (!string.IsNullOrEmpty(enc.OwnerPwd)) { ownerPassword = DocWriter.GetISOBytes(enc.OwnerPwd); } PdfReader reader = new PdfReader(this.inputPDF, ownerPassword); FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write); PdfStamper st; if (this.myCert == null) //No signature just write meta-data and quit { st = new PdfStamper(reader, fs); } else { st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi); } if (encrypt && enc != null) { enc.Encrypt(st); } //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY); st.MoreInfo = this.metadata.getMetaData(); st.XmpMetadata = this.metadata.getStreamedMetaData(); if (this.myCert == null) //No signature just write meta-data and quit { st.Close(); return; } PdfSignatureAppearance sap = st.SignatureAppearance; //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED); sap.Reason = sigAP.SigReason; sap.Contact = sigAP.SigContact; sap.Location = sigAP.SigLocation; if (sigAP.Visible) { iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page); sap.Image = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData); sap.Layer2Text = sigAP.CustomText; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null); } // Remove yellow question mark (green check mark is still used though) //sap.GetLayer(1); // The first signature is a certification //if (!sigAP.Multi) //{ // //sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; // sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING; //} PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); PdfPKCS7 sgn = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA-256", false); IDigest messageDigest = DigestUtilities.GetDigest("SHA-256"); // change for itextsharp-all-5.2.1 Stream data = sap.GetRangeStream(); byte[] buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); DateTime cal = DateTime.Now; byte[] ocsp = null; if (this.myCert.Chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]); if (url != null && url.Length > 0) { //ocsp = new OcspClientBouncyCastle(this.myCert.Chain[0], this.myCert.Chain[1], url).GetEncoded(); // change for itextsharp-all-5.2.1 ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url); } } byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); byte[] paddedSig = new byte[contentEstimated]; if (this.myCert.Tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp); System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { throw new Exception("Not enough space for signature"); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new Exception("Not enough space for signature"); } } PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); //// Lock all fields after signing (backport from iText 5.4.4) - wrong - doesn't work //PdfDictionary lockDic = new PdfDictionary(new PdfName("SigFieldLock")); //lockDic.Put(PdfName.ACTION, new PdfName("All")); //lockDic.Put(PdfName.P, new PdfNumber(1)); //dic2.Put(PdfName.LOCK, lockDic); sap.Close(dic2); //st.Close(); }
private static async Task Main(string[] args) { Console.WriteLine("CMD Signing Docs Demo..."); var amaOptions = LoadFromJsonFile(); var amaCert = LoadAmaCertificate(); var encryptionHelper = new EncryptionHelper(amaCert); var amaService = new AmaSigningService(amaOptions, encryptionHelper); Console.WriteLine("Please introduce your phone number: "); var phoneNumber = Console.ReadLine(); var userCertificatesChain = await amaService.GetUserCertificateChainAsync(phoneNumber !); var pdfToBeSigned = "d:\\code\\ama\\doc1.pdf"; var temporaryPdf = "d:\\code\\ama\\doc1_int.pdf"; var finalPdf = "d:\\code\\ama\\doc1_signed.pdf"; // freetsa -> config information: https://www.freetsa.org/guide/demonstration-digitally-signed-PDF-documents.html var tsaClient = new TSAClientBouncyCastle("https://freetsa.org/tsr"); // crl list for revocation var crlClients = new List <ICrlClient> { new CrlClientOnline(userCertificatesChain.ToArray()) }; // added ocsp client var ocspClient = new OcspClientBouncyCastle(null); var pdfSigner = new PdfSigningManager(userCertificatesChain, crlClients: crlClients, ocspClient: ocspClient, tsaClient: tsaClient); var pathToLogo = "d:\\code\\ama\\logo.jpg"; var logo = ImageDataFactory.CreateJpeg(new Uri(pathToLogo)); var hashInformation = pdfSigner.CreateTemporaryPdfForSigning(new SigningInformation(pdfToBeSigned, temporaryPdf, Reason: "Because yes", Location: "Funchal", Logo: logo)); Console.WriteLine("Please introduce your CMD signing pin: "); var cmdSigningPin = ReadSecretValueFromConsole(); var processId = await amaService.StartDocSigningProcessAsync(hashInformation.HashForSigning, "Doc1.pdf", phoneNumber !, cmdSigningPin !); Console.WriteLine($"{Environment.NewLine}Please introduce the PIN you've received on your phone"); var otpCode = Console.ReadLine(); var signature = await amaService.ConfirmDocSigningAsync(otpCode !, processId); pdfSigner.SignIntermediatePdf(new SignatureInformation(temporaryPdf, finalPdf, signature, hashInformation.NakedHash, null)); Console.WriteLine("Document signed"); Process.Start("cmd.exe ", $"/c {finalPdf}"); }
private ActionResult SignPdfFile(PdfStamper stamper, IJob job) { Signing s = job.Profile.PdfSettings.Signing; //Leave without signing //WEG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (!s.Enable) { if (stamper != null) { stamper.Close(); return(new ActionResult()); } Logger.Error("Could not create Stamper for Encryption, without Signing"); return(new ActionResult(ActionId, 104)); } //Continue for Signing s.CertificationFile = Path.GetFullPath(s.CertificationFile); if (IsValidCertificatePassword(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + s.CertificationFile + "' is wrong."); stamper.Close(); return(new ActionResult(ActionId, 105)); } if (CertificateHasPrivateKey(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + s.CertificationFile + "' has no private key."); stamper.Close(); return(new ActionResult(ActionId, 106)); } var fsCert = new FileStream(s.CertificationFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, job.Passwords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; X509CertificateEntry[] x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (int k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (s.TimeServerUrl.Trim() != "") //Timeserver with LogIn? { tsc = new TSAClientBouncyCastle(s.TimeServerUrl /*, TimeServerLogonName, TimeServerLogonPassword*/); } PdfSignatureAppearance sap = stamper.SignatureAppearance; if (tsc == null) { sap.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { sap.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } sap.Reason = s.SignReason; sap.Contact = s.SignContact; sap.Location = s.SignLocation; if (s.DisplaySignatureInPdf) { int signPage = SignPageNr(job); sap.SetVisibleSignature(new Rectangle(s.LeftX, s.LeftY, s.RightX, s.RightY), signPage, null); } var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = sap.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } DateTime cal = sap.SignDate; byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); return(new ActionResult()); }
public static void AssinaComCertificado(List <ICrlClient> crlList, byte[] File, out byte[] SignFile, 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 = "") { int Largura = 140; int Altura = 63; MemoryStream ArquivoOrigem = new MemoryStream(File); PdfReader pdfReader = new PdfReader(ArquivoOrigem); MemoryStream signedPdf = new MemoryStream(); 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, Cargo, CREACRM); 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 { RSA rsaTeste = cert.Certificado.GetRSAPrivateKey(); 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 { SignFile = signedPdf.ToArray(); try { signedPdf.Close(); signedPdf.Dispose(); } catch { } } catch (Exception ex) { SignFile = null; throw ex; } try { signedPdf.Close(); } catch (Exception ex) { } pdfReader.Close(); }
public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption Enc) { PdfReader reader = new PdfReader(this.inputPDF); FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write); PdfStamper st; if (this.myCert == null) //No signature just write meta-data and quit { st = new PdfStamper(reader, fs); } else { st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi); } if (encrypt && Enc != null) { Enc.Encrypt(st); } //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY); st.MoreInfo = this.metadata.getMetaData(); st.XmpMetadata = this.metadata.getStreamedMetaData(); if (this.myCert == null) //No signature just write meta-data and quit { st.Close(); return; } PdfSignatureAppearance sap = st.SignatureAppearance; //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED); sap.Reason = sigAP.SigReason; sap.Contact = sigAP.SigContact; sap.Location = sigAP.SigLocation; if (sigAP.Visible) { iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page); sap.Image = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData); sap.Layer2Text = sigAP.CustomText; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null); } ///// PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); PdfPKCS7 sgn = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA1", false); IDigest messageDigest = DigestUtilities.GetDigest("SHA1"); Stream data = sap.GetRangeStream(); byte[] buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); DateTime cal = DateTime.Now; byte[] ocsp = null; if (this.myCert.Chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url); } } byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); byte[] paddedSig = new byte[contentEstimated]; if (this.myCert.Tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp); System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { throw new Exception("Not enough space for signature"); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new Exception("Not enough space for signature"); } } PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); ////// //st.Close(); }
// metodo principal para el procesamiento de pdfs (firma digital adjuntos metadatos) public string SignPdf( SignRenderingMode signRenderingMode, Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto jsonToProcess, string path) { try { //var json = File.ReadAllText(path); //var jsonToProcess = JsonConvert //.DeserializeObject<Funciones.Archivos.Pdf.Dtos.PdfSign.PdfSignRequestDto>(json.Replace("<EOF>", "")); _target = jsonToProcess.outPath; _fs = GetPdfStreamFormUrlOrBase64(jsonToProcess.dataUriBase64PdfToSign); // conversor de certificados var objCP = new BcX509.X509CertificateParser(); var crlList = new List <ICrlClient>(); // buscar el certificado por numero serial var certificate = SearchCertificate(jsonToProcess.certificateSerialNumber); if (certificate == null) { return("No se encontraron certificados para el serial: " + jsonToProcess.certificateSerialNumber); } // definicion del certificado operable var objChain = new BcX509.X509Certificate[] { objCP.ReadCertificate(certificate.RawData) }; crlList.Add(new CrlClientOnline(objChain)); //TODO: habilitar la estampa cronologica (Error) (verificar tsa Timestamping Authority) // agregamos la estampa cronologica #region estampa cronologica ITSAClient tsaClient = null; IOcspClient ocspClient = null; if (jsonToProcess.addTimeStamp) { ocspClient = new OcspClientBouncyCastle(); //CertificateUtil.getTSAURL(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(certificate)); tsaClient = new TSAClientBouncyCastle(jsonToProcess.urlTSA); } #endregion estampa cronologica // cargue del pdf al lector de itextsharp var _pdfReader = new PdfReader(_fs); // cargue an memoria del pdf using (var _wfs = new MemoryStream()) { // creacion de la firma a partir del lector itextsharp y el pdf en memoria using (var objStamper = PdfStamper.CreateSignature(_pdfReader, _wfs, '\0', null, true)) { // Procesar adjuntos var attachmentIndex = 1; (jsonToProcess.dataUriBase64ListOfPdfToAttach as List <FileToAttachDto>).ForEach( (item) => { //TODO: verificar si no se va a necesitar if (!item.pathOrDataUriBase64.StartsWith("data:")) { var pfs = PdfFileSpecification.FileEmbedded(objStamper.Writer, item.fileDescription, attachmentIndex + "_" + item.fileDescription + ".pdf", null, true); objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs); } else { try { var x = StreamToByteArray(GetPdfStreamFormUrlOrBase64(item.pathOrDataUriBase64)); var pfs = PdfFileSpecification.FileEmbedded( objStamper.Writer, item.fileDescription + ".pdf", item.fileDescription + ".pdf", x, true, item.mimeType, null ); objStamper.Writer.AddFileAttachment("Adjunto número: " + attachmentIndex, pfs); //.AddFileAttachment("adjunto número: " + attachmentIndex, x, "adjunto_" + attachmentIndex + ".pdf", "adjunto " + attachmentIndex); } catch (Exception exce) { Console.WriteLine(exce.StackTrace); } } attachmentIndex++; }); // definicion de la apariencia de la firma var signatureAppearance = objStamper.SignatureAppearance; // definicion del enum itextsharp a partir del enum parametro local var mode = Enum.Parse(typeof(RenderingMode), signRenderingMode.ToString()); signatureAppearance.SignatureRenderingMode = (RenderingMode)mode; signatureAppearance.Reason = jsonToProcess.reasonToSign; signatureAppearance.Location = jsonToProcess.locationDescription; // agregar marca visual de firma digital #region agregar marca visual firma digital if (jsonToProcess.addVisibleSignMark) { // definicion de imagen desde ruta o base64 signatureAppearance.SignatureGraphic = GetImageFormUrlOrBase64(jsonToProcess.dataUriBase64SignImage); // definicion de la firma digital visible signatureAppearance.SetVisibleSignature( new Rectangle(jsonToProcess.visibleSignMarkWidth, jsonToProcess.visibleSignMarkHeight, jsonToProcess.xVisibleSignMarkPosition, jsonToProcess.yVisibleSignMarkPosition), _pdfReader.NumberOfPages, jsonToProcess.visibleSignText); } #endregion agregar marca visual firma digital // Agregar propiedades extendidas objStamper.MoreInfo = (jsonToProcess.metadata as List <MetadataDto>).ToDictionary(x => x.key, x => x.value); //TODO: verificar si no es necesario la utilizacion de XMP manual (actualmente funciona) #region xmp implementacion manual /* objStamper.Writer.CreateXmpMetadata(); * var xmp = objStamper.Writer.XmpMetadata; * * * //XMP metadatos * IXmpMeta xmp; * using (var stream = File.OpenRead(@"C:\Users\danie\OneDrive\Escritorio\xmpMetadata.xml")) * xmp = XmpMetaFactory.Parse(stream); * * foreach (var property in xmp.Properties) * { * Console.WriteLine($"Path={property.Path} Namespace={property.Namespace} Value={property.Value}"); * } * * var serializeOptions = new SerializeOptions(); * serializeOptions.UsePlainXmp = true; * var newMetadata = XmpMetaFactory.SerializeToBuffer(xmp, serializeOptions); * objStamper.XmpMetadata = newMetadata;*/ #endregion xmp implementacion manual // Firmar digitalmente var externalSignature = new X509Certificate2Signature(certificate, jsonToProcess.certificateHashAlgorithm); MakeSignature.SignDetached(signatureAppearance, externalSignature, objChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS); } var pdfFileTocreate = jsonToProcess.outPath.Replace("json", "pdf"); System.IO.File.WriteAllBytes(pdfFileTocreate, _wfs.ToArray()); Process.Start(pdfFileTocreate); return(Convert.ToBase64String(_wfs.ToArray())); } } catch (Exception exce) { WriteToFile(exce.StackTrace); WriteToFile(exce.Message); return(exce.Message); } }
private MemoryStream Assinar2(MemoryStream ArquivoOrigem, X509Certificate2 cert, ref byte[] pkcs7) { this.card = cert; X509CertificateParser x509CertificateParser = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] array = new Org.BouncyCastle.X509.X509Certificate[] { x509CertificateParser.ReadCertificate(this.card.RawData) }; PdfReader reader = new PdfReader(ArquivoOrigem); MemoryStream memoryStream = new MemoryStream(); PdfStamper pdfStamper = PdfStamper.CreateSignature(reader, memoryStream, '\0', null, true); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SetCrypto(null, array, null, PdfSignatureAppearance.SELF_SIGNED); signatureAppearance.Reason = this.proposito; signatureAppearance.Contact = this.contato; signatureAppearance.Location = this.localizacao; signatureAppearance.CryptoDictionary = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")) { Reason = signatureAppearance.Reason, Location = signatureAppearance.Location, Contact = signatureAppearance.Contact, Date = new PdfDate(signatureAppearance.SignDate) }; int num = 15000; Dictionary <PdfName, int> dictionary = new Dictionary <PdfName, int>(); dictionary[PdfName.CONTENTS] = num * 2 + 2; signatureAppearance.PreClose(dictionary); //PdfPKCS7 pdfPKCS = new PdfPKCS7(null, array, null, "SHA1", false); PdfPKCS7 pdfPKCS = new PdfPKCS7(null, array, null, "MD5", false); IDigest digest = DigestUtilities.GetDigest("MD5"); Stream rangeStream = signatureAppearance.GetRangeStream(); byte[] array2 = new byte[8192]; int length; while ((length = rangeStream.Read(array2, 0, array2.Length)) > 0) { digest.BlockUpdate(array2, 0, length); } byte[] array3 = new byte[digest.GetDigestSize()]; digest.DoFinal(array3, 0); DateTime now = DateTime.Now; byte[] ocsp = null; if (array.Length >= 2) { string oCSPURL = PdfPKCS7.GetOCSPURL(array[0]); if (oCSPURL != null && oCSPURL.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(array[0], array[1], oCSPURL); } } byte[] authenticatedAttributeBytes = pdfPKCS.GetAuthenticatedAttributeBytes(array3, now, ocsp); byte[] digest2 = Assinar.SignSHA1withRSA(this.card, authenticatedAttributeBytes); pdfPKCS.SetExternalDigest(digest2, array3, "RSA"); byte[] array4 = new byte[num]; byte[] encodedPKCS = pdfPKCS.GetEncodedPKCS7(array3, now, null, ocsp); pkcs7 = encodedPKCS; Array.Copy(encodedPKCS, 0, array4, 0, encodedPKCS.Length); if (num + 2 < encodedPKCS.Length) { throw new ApplicationException("Não há espaço suficiente para assinatura."); } PdfDictionary pdfDictionary = new PdfDictionary(); pdfDictionary.Put(PdfName.CONTENTS, new PdfString(array4).SetHexWriting(true)); signatureAppearance.Close(pdfDictionary); //pdfStamper. return(memoryStream); }
public static string SignFile(string fileName, PdfSignatureParameters parameters, IDigitalSignatureCertificateSelector certificateSelector) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("Filename must be given", nameof(fileName)); } if (!File.Exists(fileName)) { throw new ArgumentException($"File {fileName} not found."); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } if (certificateSelector == null) { throw new ArgumentNullException(nameof(certificateSelector)); } string tempPath = string.Empty; try { tempPath = GetTempPath(parameters.TempFolderPath); string targetFilePath = GetTargetFilePath(parameters.TempFolderPath, parameters.TargetFilePath); var signingCertificates = CertificateHelper.GetSigningCertificates(certificateSelector); // Two clients for checking certificate revocation // * Online Certificate Status Protocol (OCSP) client // * Certificate Revocation Lists (CRL) client with online checking // Certificate will be checked when the signature is made OcspClientBouncyCastle oscpClient = new OcspClientBouncyCastle(null); List <ICrlClient> clrClients = new List <ICrlClient> { new CrlClientOnline(signingCertificates.FinalChain) }; using (FileStream targetFileStream = new FileStream(targetFilePath, FileMode.Create)) using (PdfReader reader = new PdfReader(fileName)) using (PdfStamper stamper = PdfStamper.CreateSignature(reader, targetFileStream, '0', tempPath, true)) { PdfSignatureAppearance appearance = GetPdfSignatureAppearance(signingCertificates, stamper, reader, parameters); CreateSignature(signingCertificates, appearance, clrClients, oscpClient); } return(targetFilePath); } finally { try { if (!string.IsNullOrWhiteSpace(tempPath) && File.Exists(tempPath)) { File.Delete(tempPath); } } catch (Exception) { } } }
private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords) { var signing = profile.PdfSettings.Signature; if (!signing.Enabled) //Leave without signing { return; } Logger.Debug("Start signing file."); signing.CertificateFile = Path.GetFullPath(signing.CertificateFile); if (string.IsNullOrEmpty(jobPasswords.PdfSignaturePassword)) { Logger.Error("Launched signing without certification password."); throw new ProcessingException("Launched signing without certification password.", 12204); } if (IsValidCertificatePassword(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong."); throw new ProcessingException( "Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.", 12200); } if (CertificateHasPrivateKey(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key."); throw new ProcessingException( "Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.", 12201); } var fsCert = new FileStream(signing.CertificateFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, jobPasswords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; var x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (var k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim())) { if (!signing.TimeServerIsSecured) { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl); } else { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName, signing.TimeServerPassword); } } var psa = stamper.SignatureAppearance; if (tsc == null) { psa.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { psa.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } if (!profile.PdfSettings.Signature.AllowMultiSigning) { //Lock PDF, except for annotations and form filling (irrelevant for clawPDF) psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS; } psa.Reason = signing.SignReason; psa.Contact = signing.SignContact; psa.Location = signing.SignLocation; if (signing.DisplaySignatureInDocument) { var signPage = SignPageNr(stamper, signing); psa.SetVisibleSignature(new Rectangle(signing.LeftX, signing.LeftY, signing.RightX, signing.RightY), signPage, null); } var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = psa.Reason; dic.Location = psa.Location; dic.Contact = psa.Contact; dic.Date = new PdfDate(psa.SignDate); psa.CryptoDictionary = dic; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; psa.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); var messageDigest = DigestUtilities.GetDigest(hashAlgorithm); var data = psa.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { var url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } var cal = psa.SignDate; var sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = null; try { encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); } catch (Exception ex) { throw new ProcessingException( ex.GetType() + " while connecting to timeserver (can't connect to timeserver): " + ex.Message, 12205); } if (contentEstimated + 2 < encodedSigTsa.Length) { throw new ProcessingException( "Not enough space for signature", 12202); } } else { var encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new ProcessingException("Not enough space for signature", 12203); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); psa.Close(dic2); }
private void CompletionPdf(byte[] invoiceMemoryStream, List <FileStream> attachmentFiles, string fileName) { var reader = new PdfReader(invoiceMemoryStream); var document = new Document(reader.GetPageSizeWithRotation(1)); var pdfMerge = new MemoryStream(); var pdfCopyProvider = new PdfCopy(document, pdfMerge); document.Open(); var pages = new List <PdfImportedPage>(); GetAllPages(reader, pdfCopyProvider, pages); foreach (var attachmentReader in attachmentFiles.Select(attachmentFile => new PdfReader(attachmentFile))) { GetAllPages(attachmentReader, pdfCopyProvider, pages); attachmentReader.Close(); } foreach (var pdfImportedPage in pages) { pdfCopyProvider.AddPage(pdfImportedPage); } document.Close(); reader.Close(); pdfCopyProvider.Close(); pdfMerge.Seek(0, SeekOrigin.Begin); var readerWithoutSign = new PdfReader(pdfMerge); var finalOutput = new FileStream(fileName, FileMode.Create, FileAccess.Write); var tsa = new TsaClientBouncyCastle("https://freetsa.org/tsr"); int contentEstimated = (int)pdfMerge.Length; var st = PdfStamper.CreateSignature(readerWithoutSign, finalOutput, '\0', null, true); var sap = st.SignatureAppearance; var cert = new Cert("EFZ.pfx", "Lea10985"); sap.SetCrypto(cert.Akp, cert.Chain, null, PdfSignatureAppearance.SelfSigned); sap.Reason = "Archived digital signature"; sap.Contact = "EFZ"; sap.Location = "EFZ"; sap.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; sap.SetCrypto(null, cert.Chain, null, PdfSignatureAppearance.VerisignSigned); var dic = new PdfSignature(PdfName.AdobePpklite, PdfName.AdbePkcs7Detached); dic.Put(PdfName.TYPE, PdfName.Stamp); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; var exc = new Dictionary <PdfName, int>(); exc[PdfName.Contents] = contentEstimated * 2 + 2; sap.PreClose(new Hashtable(exc)); var sgn = new PdfPkcs7(cert.Akp, cert.Chain, null, "SHA1", false); var data = sap.RangeStream; var messageDigest = DigestUtilities.GetDigest("SHA1"); byte[] buf = new byte[8192]; 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); var cal = DateTime.UtcNow; byte[] tsToken = tsa.GetTimeStampToken(null, tsImprint); byte[] ocsp = null; if (cert.Chain.Length >= 2) { String url = PdfPkcs7.GetOcspurl(cert.Chain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle(cert.Chain[0], cert.Chain[1], url).GetEncoded(); } } byte[] sh = sgn.GetAuthenticatedAttributeBytes(tsImprint, cal, ocsp); sgn.Update(sh, 0, sh.Length); byte[] encodedSig = sgn.GetEncodedPkcs7(tsImprint, cal, tsa, ocsp); if (contentEstimated + 2 < encodedSig.Length) { throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); var dic2 = new PdfDictionary(); dic2.Put(PdfName.Contents, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); finalOutput.Close(); finalOutput.Dispose(); }
public static void AssinaComToken(Stream File, out byte[] SignFile, CertSimples cert, float X, float 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-1", 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 = "") { int Largura = 155; int Altura = 63; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm); PdfReader pdfReader = new PdfReader(File); MemoryStream signedPdf = new MemoryStream(); //cria a assinatura //PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true); string path = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("hhMMddHHmmss") + ".pdf", true); Bitmap bmp = Graphic.ConfiguraBMP(cert, out Altura, Tipo); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader); TSAClientBouncyCastle tsaClient = null; if (AddTimeStamper) { tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); } IOcspClient ocspClient = new OcspClientBouncyCastle(); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); if (AplicaPolitica) { SignaturePolicyInfo spi = PoliticaDaAssinatura(); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); } else { MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); } try { SignFile = signedPdf.ToArray(); //SignFile = INB.Assinador.Helper.Funcoes.ToByteArray(teste); //MemoryStream teste = (MemoryStream)signatureAppearance.TempFile; //signedPdf.Flush(); //SignFile // SignFile = new MemoryStream(ArquivoAssinado); // signedPdf.CopyTo(); try { signedPdf.Close(); signedPdf.Dispose(); } catch { } } catch (Exception ex) { SignFile = null; throw ex; } try { signedPdf.Close(); } catch (Exception ex) {} pdfReader.Close(); try { pdfReader.Dispose(); } catch { } }
//public static void AssinaComToken_OLD(string FileName, string SignFileName, X509Certificate2 cert, float X, float Y, int Pagina, double Escala, bool SeloCargo = false, bool SeloCREA = false, bool SeloCRM = false, string Cargo = "", string CREACRM = "", bool AddTimeStamper = true, string urlTimeStamper = "https://freetsa.org/tsr", string timeStampUser = "", string timeStampPass = "", string Reason = "Assinatura Digital", bool AplicaPolitica = false, string MyDigestAlgorithm = "SHA-1", string Contact = "", string Location = "Indústrias Nucleares do Brasil S/A - INB", string Creator = "Assinador da INB", bool SeloCertifico = false) //{ // string SourcePdfFileName = FileName; // string DestPdfFileName = SignFileName; // int Largura = 155; // int Altura = 63; // Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); // Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }; // IExternalSignature externalSignature = new X509Certificate2Signature(cert, MyDigestAlgorithm); // PdfReader pdfReader = new PdfReader(SourcePdfFileName); // FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); //the output pdf file // //cria a assinatura // PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', "temp" + signedPdf, true); // PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; // Bitmap bmp = INB.Assinador.Helper.Graphic.ConfiguraBMP(cert, SeloCargo, SeloCREA, SeloCRM, Cargo, CREACRM, out Altura, SeloCertifico); // //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA. // ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Escala, Pagina, pdfReader); // //ADICIONA O CARIMBO DO TEMPO. // TSAClientBouncyCastle tsaClient = null; // if (AddTimeStamper) // { // //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll // //urlTimeStamper = "http://timestamp.apple.com/ts01"; // tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); // } // IOcspClient ocspClient = new OcspClientBouncyCastle(); // List<ICrlClient> crlList = new List<ICrlClient>(); // crlList.Add(new CrlClientOnline(chain)); // //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA. // if (AplicaPolitica) // { // SignaturePolicyInfo spi = PoliticaDaAssinatura(); // MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); // } // else // { // MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); // } // try { signedPdf.Flush(); } // catch { } // try { signedPdf.Close(); } catch { }; // pdfReader.Close(); // try { // pdfReader.Dispose(); // } // catch { } //} public static void AssinaComToken(string FileName, string SignFileName, CertSimples cert, float X, float 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-1", 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 = 155; int Altura = 63; Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.Certificado.RawData) }; //IExternalSignature externalSignature = new X509Certificate2Signature(cert.Certificado, MyDigestAlgorithm); RSACryptoServiceProvider rsa; RSACryptoServiceProvider Provider; IExternalSignature externalSignature = null; if (cert.Certificado.PrivateKey is RSACryptoServiceProvider) { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } else { rsa = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; Provider = (RSACryptoServiceProvider)cert.Certificado.PrivateKey; externalSignature = new AsymmetricAlgorithmSignature(Provider, MyDigestAlgorithm); } PdfReader pdfReader = new PdfReader(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create, FileAccess.ReadWrite); //the output pdf file string path = System.AppDomain.CurrentDomain.BaseDirectory + "Temp\\"; //cria a assinatura PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', path + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf", true); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; Bitmap bmp = INB.Assinador.Model.Graphic.ConfiguraBMP(cert, out Altura, Tipo); //CONFIGURA A APARÊNCIA DO SELO DA ASSINATURA. ConfiguraAparenciaAssinatura(signatureAppearance, Reason, Contact, Location, Creator, bmp, Altura, Largura, X, Y, Rotation, Pagina, pdfReader); //ADICIONA O CARIMBO DO TEMPO. TSAClientBouncyCastle tsaClient = null; if (AddTimeStamper) { //urlTimeStamper = http://timestamp.globalsign.com/scripts/timestamp.dll //urlTimeStamper = "http://timestamp.apple.com/ts01"; tsaClient = new TSAClientBouncyCastle(urlTimeStamper, timeStampUser, timeStampPass, TSAClientBouncyCastle.DEFAULTTOKENSIZE, MyDigestAlgorithm); } IOcspClient ocspClient = new OcspClientBouncyCastle(); List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline(chain)); //Nota 2: O hash da política de assinatura no atributo id-aa-ets-sigPolicyId da assinatura deve ser o hash interno que está na própria PA e não o hash da PA que se encontra publicada na LPA. if (AplicaPolitica) { SignaturePolicyInfo spi = PoliticaDaAssinatura(); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES, spi); } else { MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CADES); } try { signedPdf.Flush(); } catch { } try { signedPdf.Close(); } catch { }; pdfReader.Close(); try { pdfReader.Dispose(); } catch { } }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); String tsaUrl = properties.GetProperty("TSAURL"); String tsaUser = properties.GetProperty("TSAUSERNAME"); String tsaPass = properties.GetProperty("TSAPASSWORD"); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); 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; } IOcspClient ocspClient = new OcspClientBouncyCastle(null); ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass); C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize(); bool succeeded = false; int estimatedSize = 1000; while (!succeeded) { try { Console.WriteLine("Attempt: " + estimatedSize + " bytes"); app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, tsaClient, estimatedSize); succeeded = true; Console.WriteLine("Succeeded!"); } catch (IOException ioe) { Console.WriteLine("Not succeeded: " + ioe.Message); estimatedSize += 50; } } }
public void Button3Click(object sender, System.EventArgs e) { if (inputBox.Text != null) { string filePDF = inputBox.Text; try { X509Certificate2 card = GetCertificate(); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) }; //ricreo il percorso con il nome del novo file string file = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")).ToLowerInvariant(); string NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf".ToLowerInvariant(); PdfReader reader = new PdfReader(filePDF); PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked); PdfSignatureAppearance sap = stp.SignatureAppearance; if (tsaCbx.Checked) { ITSAClient tsc = new TSAClientBouncyCastle(TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } if (SigVisible.Checked) { sap.Reason = cbRagioneSingolo.Text; sap.Contact = Contacttext.Text; sap.Location = Locationtext.Text; if (sigImgBox.Image != null) { MemoryStream ms = new MemoryStream(); sigImgBox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); sap.Image = ms.ToArray() == null ? null : iTextSharp.text.Image.GetInstance(ms.ToArray()); ms.Close(); } sap.SetVisibleSignature(new iTextSharp.text.Rectangle((float)sigPosX.Value, (float)sigPosY.Value, (float)sigPosX.Value + (float)sigWidth.Value, (float)sigPosY.Value + (float)sigHeight.Value), Convert.ToInt32(numberOfPagesUpDown.Value), null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.Description; //.NameAndDescription; PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.Date = new PdfDate(sap.SignDate); dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); if (sap.Reason != null) { dic.Reason = sap.Reason; } if (sap.Location != null) { dic.Location = sap.Location; } if (sap.Contact != null) { dic.Contact = sap.Contact; } sap.CryptoDictionary = dic; int contentEstimated = 15000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); IDigest messageDigest = DigestUtilities.GetDigest("SHA256"); //add Stream s = sap.GetRangeStream(); MemoryStream ss = new MemoryStream(); int read = 0; byte[] buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { ss.Write(buff, 0, read); messageDigest.BlockUpdate(buff, 0, read); //add } //-------------------------------------------- byte[] hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); DateTime cal = DateTime.Now; byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); MessageBox.Show(ocsp.ToString()); } } //------------------------------------------------------------------- //TEST TIMESTAMP CON BOUNCYCASTLE //------------------------------------------------------------------- /* * TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); * // Dummy request * TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, hash, BigInteger.ValueOf(100)); * byte[] reqData = request.GetEncoded(); * HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create("http://localhost:8080/signserver/process?workerId=1"); * httpReq.Method = "POST"; * httpReq.ContentType = "application/timestamp-query"; * httpReq.ContentLength = reqData.Length; * // Write the request content * Stream reqStream = httpReq.GetRequestStream(); * reqStream.Write(reqData, 0, reqData.Length); * reqStream.Close(); * HttpWebResponse httpResp = (HttpWebResponse) httpReq.GetResponse(); * // Read the response * Stream respStream = new BufferedStream(httpResp.GetResponseStream()); * TimeStampResponse response = new TimeStampResponse(respStream); * respStream.Close(); * //MessageBox.Show(response.TimeStampToken.TimeStampInfo.GenTime.ToString()); */ //------------------------------------------------------------------- //TEST TIMESTAMP CON BOUNCYCASTLE //------------------------------------------------------------------- //===================================QUI FIRMO byte[] pk; if (tsaCbx.Checked) { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } else { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, "", "", ""); } //-------------------------------------------- byte[] outc = new byte[contentEstimated]; PdfDictionary dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sap.Close(dic2); MessageBox.Show("File firmato correttamente", "Operazione Completata"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }