public void CASignProcess(PdfAuthImg authImg) { PdfReader pdfReader = null; PdfStamper pdfStamper = null; FileStream signedPdf = null; try { if (string.IsNullOrEmpty(BasePdf)) { throw new Exception("PDF源路径为空"); } if (string.IsNullOrEmpty(StampPdf)) { throw new Exception("PDF输出路径为空"); } pdfReader = new PdfReader(BasePdf); signedPdf = new FileStream(StampPdf, FileMode.OpenOrCreate); pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, true); if (transScalH == 0 || transScalV == 0) { float width = pdfReader.GetPageSizeWithRotation(1).Width; float height = pdfReader.GetPageSizeWithRotation(1).Height; if (m_PaperWidth == 0 || m_PaperHeight == 0) { m_PaperWidth = (float)(width / 72 * 25.4); m_PaperHeight = (float)(height / 72 * 25.4); } float cmpOne = width, cmpTwo = height, cmpThr = m_PaperWidth, cmpFour = m_PaperHeight; if (height > width) { cmpOne = height; cmpTwo = width; } if (m_PaperHeight > m_PaperWidth) { cmpThr = m_PaperHeight; cmpFour = m_PaperWidth; } transScalH = cmpOne / cmpThr; transScalV = cmpTwo / cmpFour; } X509Certificate2 cert = null; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 myX509Certificate2 in store.Certificates) { if (myX509Certificate2.Subject.Contains(authImg.CertName)) { cert = myX509Certificate2; } } store.Close(); if (cert == null) { return; } float m_llx = authImg.AbsoluteX; float m_lly = authImg.AbsoluteY; float m_urx = m_llx + authImg.FitWidth; float m_ury = m_lly + authImg.FitHeight; if (authImg.Rotation == 90 || authImg.Rotation == 270 || authImg.Rotation == -90) { m_urx = m_llx + authImg.FitHeight; m_ury = m_lly + authImg.FitWidth; } var stampArea = new Rectangle(m_llx * transScalH, m_lly * transScalV, m_urx * transScalH, m_ury * transScalV); var img = Image.GetInstance(authImg.ImagePath); img.Rotation = (float)(authImg.Rotation / 180 * Math.PI); X509CertificateParser cp = new X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SignatureGraphic = img; signatureAppearance.SetVisibleSignature(stampArea, authImg.PageNum, "Signature" + Index.ToString()); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC; signatureAppearance.SignDate = System.DateTime.Now; signatureAppearance.Reason = "12345"; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, TsaClient, 0, CryptoStandard.CMS); } catch (System.Exception ex) { throw ex; } finally { if (pdfStamper != null) { pdfStamper.Close(); } if (pdfReader != null) { pdfReader.Close(); } if (signedPdf != null) { signedPdf.Close(); } pdfStamper = null; pdfReader = null; signedPdf = null; } }
/// <summary> /// Assina um pdf com um certificado válido /// </summary> /// <param name="certificate">X509 Certificado</param> /// <param name="dadosAssinatura">Dados da assinatura (DadosAssinatura)</param> /// <returns></returns> public static byte[] AssinarPdf(X509Certificate2 certificate, DadosAssinatura dadosAssinatura) { try { // ler arquivo e insere dados de assinatura using (PdfReader reader = new PdfReader(dadosAssinatura.Arquivo)) { using (MemoryStream fout = new MemoryStream()) { PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0', null, true); // texto marca d'água Font f = new Font(Font.FontFamily.TIMES_ROMAN, 8); string[] dados = certificate.GetNameInfo(X509NameType.SimpleName, false).Split(':'); Phrase pAssinado = new Phrase($@"Este documento foi assinado digitalmente por: {dados[0]}", f); // Imagem marca d'água //Image img = dadosAssinatura.Imagem; float w = 200F; float h = 75.2F; // Transparência PdfGState gs1 = new PdfGState(); // Propriedades PdfContentByte over; Rectangle pagesize; int n = reader.NumberOfPages; //Página var pagina = 1; bool todasPaginas = false; pagesize = reader.GetPageSizeWithRotation(pagina); switch (dadosAssinatura.PaginaAssinatura) { case EnumPaginaAssinatura.PRIMEIRA: pagina = 1; break; case EnumPaginaAssinatura.ULTIMA: pagina = reader.NumberOfPages; break; case EnumPaginaAssinatura.TODAS: todasPaginas = true; break; default: pagina = 1; break; } float x, y, xr = 0, hr = 0, yr = 0, wr = 0; //Posição da assinatura switch (dadosAssinatura.Posicao) { case EnumPosicao.ACIMA_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 0.5F; wr = w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ACIMA_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Top * 0.88); xr = pagesize.Right * 0.97F; wr = xr - w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ABAIXO_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Bottom * 0.88); xr = x * 0.5F; wr = w; yr = y; hr = h; break; case EnumPosicao.ABAIXO_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Bottom * 0.88); xr = x * 1.53F; wr = w * 1.9F; yr = y; hr = h; break; case EnumPosicao.ABAIXO_CENTRO: x = (pagesize.Right * 1.74f - pagesize.Left) / 1.32f; y = (float)(pagesize.Bottom * 0.76); xr = x * 1.53F; wr = w * 1.53F; yr = y; hr = h; break; default: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 1.53F; wr = w * 1.9F; break; } PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; appearance.Layer2Text = ""; appearance.Layer4Text = ""; Rectangle rect = new Rectangle(wr, hr, xr, yr); //Plota a assinatura no pdf if (todasPaginas) { for (int i = 1; i <= n; i++) { over = stamper.GetOverContent(i); over.SaveState(); over.SetGState(gs1); //over.AddImage(img, w, 0, 0, h, x, y); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 57, y + 15, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pCodigAut, x + 84.5f, y + 5, 0); over.RestoreState(); } } else { over = stamper.GetOverContent(pagina); over.SaveState(); over.SetGState(gs1); //over.AddImage(img, w, 0, 0, h, x, y); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 57, y + 15, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pCodigAut, x + 84.5f, y + 5, 0); over.RestoreState(); } ICollection <Org.BouncyCastle.X509.X509Certificate> certChain; IExternalSignature es = ResolveExternalSignatureFromCertStore(certificate, dadosAssinatura.CertificadoValido, out certChain); //Autenticação da assinatura digital MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CADES); stamper.Close(); return(fout.ToArray()); } } } catch (Exception ex) { throw new Exception($"Erro durante assinatura digital do pdf: {ex.Message}"); } }
/// <summary> /// Main method specifying where program execution is to begin /// </summary> /// <param name="args">Command line arguments passed to the program</param> public static void Main(string[] args) { try { // Parse command line arguments string pkcs11Library = null; int listTokens = 0; int listObjects = 0; int sign = 0; string tokenSerial = null; string tokenLabel = null; string pin = null; string keyLabel = null; string keyId = null; string inputPdf = null; string outputPdf = null; string hashAlg = null; string certsDir = null; //if (args.Length == 0) // ExitWithHelp(null); int i = 0; #region List tokens pkcs11Library = "acos5evopkcs11.dll"; listTokens = 1; #endregion #region List objects //pkcs11Library = "acos5evopkcs11.dll"; listObjects = 1; pin = "12345678"; //tokenSerial = "902000A1C4650A00"; #endregion #region commented //while (i < args.Length) //{ // switch (args[i]) // { // case _argPkcs11Library: // pkcs11Library = args[++i]; // break; // case _argListTokens: // listTokens = 1; // break; // case _argListObjects: // listObjects = 1; // break; // case _argSign: // sign = 1; // break; // case _argTokenSerial: // tokenSerial = args[++i]; // break; // case _argTokenLabel: // tokenLabel = args[++i]; // break; // case _argPin: // pin = args[++i]; // break; // case _argKeyLabel: // keyLabel = args[++i]; // break; // case _argKeyId: // keyId = args[++i]; // break; // case _argInputPdf: // inputPdf = args[++i]; // break; // case _argOutputPdf: // outputPdf = args[++i]; // break; // case _argHashAlg: // hashAlg = args[++i]; // break; // case _argCertsDir: // certsDir = args[++i]; // break; // default: // ExitWithHelp("Invalid argument: " + args[i]); // break; // } // i++; //} #endregion //// Validate operation modes //if (listTokens + listObjects + sign != 1) // ExitWithHelp(string.Format("Argument \"{0}\", \"{1}\" or \"{2}\" has to be specified", _argListTokens, _argListObjects, _argSign)); // Handle "--list-tokens" operation mode if (listTokens == 1) { // Validate command line arguments if (string.IsNullOrEmpty(pkcs11Library)) { ExitWithHelp("Required argument: " + _argPkcs11Library); } if (!string.IsNullOrEmpty(tokenSerial)) { ExitWithHelp("Unexpected argument: " + _argTokenSerial); } if (!string.IsNullOrEmpty(tokenLabel)) { ExitWithHelp("Unexpected argument: " + _argTokenLabel); } //if (!string.IsNullOrEmpty(pin)) // ExitWithHelp("Unexpected argument: " + _argPin); if (!string.IsNullOrEmpty(keyLabel)) { ExitWithHelp("Unexpected argument: " + _argKeyLabel); } if (!string.IsNullOrEmpty(keyId)) { ExitWithHelp("Unexpected argument: " + _argKeyId); } if (!string.IsNullOrEmpty(inputPdf)) { ExitWithHelp("Unexpected argument: " + _argInputPdf); } if (!string.IsNullOrEmpty(outputPdf)) { ExitWithHelp("Unexpected argument: " + _argOutputPdf); } if (!string.IsNullOrEmpty(hashAlg)) { ExitWithHelp("Unexpected argument: " + _argHashAlg); } if (!string.IsNullOrEmpty(certsDir)) { ExitWithHelp("Unexpected argument: " + _argCertsDir); } // Perform requested operation using (Pkcs11Explorer pkcs11Explorer = new Pkcs11Explorer(pkcs11Library)) { Console.WriteLine("Listing available tokens"); int j = 1; List <Token> tokens = pkcs11Explorer.GetTokens(); foreach (Token token in tokens) { Console.WriteLine(); Console.WriteLine("Token no." + j); Console.WriteLine(" Manufacturer: " + token.ManufacturerId); Console.WriteLine(" Model: " + token.Model); Console.WriteLine(" Serial number: " + token.SerialNumber); Console.WriteLine(" Label: " + token.Label); tokenSerial = token.SerialNumber; j++; } } } //using (Pkcs11Explorer pkcs11Explorer = new Pkcs11Explorer(pkcs11Library)) //{ // Console.WriteLine("writing certificate"); // //var certData = File.ReadAllBytes("root.pfx"); //"11325467985631_pri.key"); //"test.cer"); // //pkcs11Explorer.Write(pin, certData); // //var certDataPrivate = File.ReadAllBytes("root.pfx"); // //pkcs11Explorer.WritePrivate(pin, certDataPrivate, "Xisys88@"); // //pkcs11Explorer.ConvertPfxToPem("localhost.pfx", "12345678", "localhost.pem"); // pkcs11Explorer.Clear(pin); // var certDataPrivate = File.ReadAllBytes("localhost.pfx"); // pkcs11Explorer.WritePrivate(pin, certDataPrivate, "12345678"); //} // Handle "--list-objects" operation mode if (listObjects == 1) { // Validate command line arguments if (string.IsNullOrEmpty(pkcs11Library)) { ExitWithHelp("Required argument: " + _argPkcs11Library); } if (string.IsNullOrEmpty(tokenSerial) && string.IsNullOrEmpty(tokenLabel)) { ExitWithHelp("Required argument: " + _argTokenSerial + " and/or " + _argTokenLabel); } if (string.IsNullOrEmpty(pin)) { ExitWithHelp("Required argument: " + _argPin); } if (!string.IsNullOrEmpty(keyLabel)) { ExitWithHelp("Unexpected argument: " + _argKeyLabel); } if (!string.IsNullOrEmpty(keyId)) { ExitWithHelp("Unexpected argument: " + _argKeyId); } if (!string.IsNullOrEmpty(inputPdf)) { ExitWithHelp("Unexpected argument: " + _argInputPdf); } if (!string.IsNullOrEmpty(outputPdf)) { ExitWithHelp("Unexpected argument: " + _argOutputPdf); } if (!string.IsNullOrEmpty(hashAlg)) { ExitWithHelp("Unexpected argument: " + _argHashAlg); } if (!string.IsNullOrEmpty(certsDir)) { ExitWithHelp("Unexpected argument: " + _argCertsDir); } // Perform requested operation using (Pkcs11Explorer pkcs11Explorer = new Pkcs11Explorer(pkcs11Library)) { Console.WriteLine(string.Format("Listing objects available on token with serial \"{0}\" and label \"{1}\"", tokenSerial, tokenLabel)); // Find requested token Token foundToken = null; List <Token> tokens = pkcs11Explorer.GetTokens(); foreach (Token token in tokens) { if (!string.IsNullOrEmpty(tokenLabel)) { if (0 != String.Compare(tokenLabel, token.Label, StringComparison.InvariantCultureIgnoreCase)) { continue; } } if (!string.IsNullOrEmpty(tokenSerial)) { if (0 != String.Compare(tokenSerial, token.SerialNumber, StringComparison.InvariantCultureIgnoreCase)) { continue; } } foundToken = token; break; } if (foundToken == null) { throw new TokenNotFoundException(string.Format("Token with serial \"{0}\" and label \"{1}\" was not found", tokenSerial, tokenLabel)); } // Get private keys and certificates stored in requested token List <PrivateKey> privateKeys = null; List <Certificate> certificates = null; pkcs11Explorer.GetTokenObjects(foundToken, true, pin, out privateKeys, out certificates); // Print private keys int j = 1; foreach (PrivateKey privateKey in privateKeys) { Console.WriteLine(); Console.WriteLine("Private key #" + j); int[] matchingCertIds = GetMatchingCertIds(privateKey, certificates); Console.WriteLine(" Matching certs: " + PrintMatchingIds(matchingCertIds)); Console.WriteLine(" ID (CKA_ID): " + privateKey.Id); Console.WriteLine(" Label (CKA_LABEL): " + privateKey.Label); // Print public part of RSA key if ((privateKey.PublicKey != null) && (privateKey.PublicKey is RsaKeyParameters)) { RsaKeyParameters rsa = privateKey.PublicKey as RsaKeyParameters; Console.WriteLine(" RSA exponent: " + ConvertUtils.BytesToHexString(rsa.Exponent.ToByteArrayUnsigned())); Console.WriteLine(" RSA public modulus: " + ConvertUtils.BytesToHexString(rsa.Modulus.ToByteArrayUnsigned())); } j++; } // Print certificates int k = 1; foreach (Certificate certificate in certificates) { Console.WriteLine(); Console.WriteLine("Certificate #" + k); int[] matchingKeyIds = GetMatchingKeyIds(certificate, privateKeys); Console.WriteLine(" Matching keys: " + PrintMatchingIds(matchingKeyIds)); X509Certificate2 x509Cert = CertUtils.ToDotNetObject(certificate.Data); try { Console.WriteLine($"Saving certificate to file exported{k}.cer"); File.WriteAllBytes($"exported{k}.cer", x509Cert.Export(X509ContentType.Cert)); } catch (Exception e) { Console.WriteLine("Error saving certificate: " + e); } Console.WriteLine(" ID (CKA_ID): " + certificate.Id); Console.WriteLine(" Label (CKA_LABEL): " + certificate.Label); Console.WriteLine(" Serial number: " + x509Cert.SerialNumber); Console.WriteLine(" Subject DN: " + x509Cert.Subject); Console.WriteLine(" Issuer DN: " + x509Cert.Issuer); Console.WriteLine(" Not before: " + x509Cert.NotBefore); Console.WriteLine(" Not after: " + x509Cert.NotAfter); // Print certified public RSA key if ((certificate.PublicKey != null) && (certificate.PublicKey is RsaKeyParameters)) { RsaKeyParameters rsa = certificate.PublicKey as RsaKeyParameters; Console.WriteLine(" RSA exponent: " + ConvertUtils.BytesToHexString(rsa.Exponent.ToByteArrayUnsigned())); Console.WriteLine(" RSA public modulus: " + ConvertUtils.BytesToHexString(rsa.Modulus.ToByteArrayUnsigned())); } k++; } } } // Handle "--sign" operation mode if (sign == 1) { // Use SHA256 as default hashing algorithm HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Validate command line arguments (_argHashAlg and _argCertsDir are optional) if (string.IsNullOrEmpty(pkcs11Library)) { ExitWithHelp("Required argument: " + _argPkcs11Library); } if (string.IsNullOrEmpty(tokenSerial) && string.IsNullOrEmpty(tokenLabel)) { ExitWithHelp("Required argument: " + _argTokenSerial + " and/or " + _argTokenLabel); } if (string.IsNullOrEmpty(pin)) { ExitWithHelp("Required argument: " + _argPin); } if (string.IsNullOrEmpty(keyLabel) && string.IsNullOrEmpty(keyId)) { ExitWithHelp("Required argument: " + _argKeyLabel + " and/or " + _argKeyId); } if (string.IsNullOrEmpty(inputPdf)) { ExitWithHelp("Required argument: " + _argInputPdf); } if (string.IsNullOrEmpty(outputPdf)) { ExitWithHelp("Required argument: " + _argOutputPdf); } if (!string.IsNullOrEmpty(hashAlg)) { hashAlgorithm = (HashAlgorithm)Enum.Parse(typeof(HashAlgorithm), hashAlg); } // Perform requested operation using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(pkcs11Library, tokenSerial, tokenLabel, pin, keyLabel, keyId, hashAlgorithm)) { Console.WriteLine(string.Format("Signing PDF document \"{0}\" using private key with ID \"{1}\" and label \"{2}\" stored on token with serial \"{3}\" and label \"{4}\"", inputPdf, keyId, keyLabel, tokenSerial, tokenLabel)); // Read signing certificate from the token byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // Read all certificates stored on the token List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Read additional certificates from directory if (!string.IsNullOrEmpty(certsDir)) { foreach (string file in Directory.GetFiles(certsDir)) { otherCertificates.Add(File.ReadAllBytes(file)); } } // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(inputPdf)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(outputPdf, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } } } catch (Exception ex) { Console.WriteLine(@"Operation error: " + ex.GetType() + " - " + ex.Message); Console.WriteLine(ex.StackTrace); //Environment.Exit(_exitError); } //Environment.Exit(_exitSuccess); Console.WriteLine("done"); Console.ReadKey(); }
private DocuResponse SignDocumentWithPin(DocuRequest doc) { //Sign from SmartCard //note : ProviderName and KeyContainerName can be found with the dos command : CertUtil -ScInfo DocuResponse respo = new DocuResponse(); X509Store store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2 cert = null; if (doc.ProviderName == "") { respo.HasError = true; respo.ErrorMessage = "Per te firmosur me certifikaten tuaj duhet te jepni Provider Name"; return(respo); } foreach (X509Certificate2 cert2 in store.Certificates) { if (cert2.HasPrivateKey) { RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey; if (rsa == null) { continue; // not smart card cert again } if (rsa.CspKeyContainerInfo.HardwareDevice) // sure - smartcard { if (rsa.CspKeyContainerInfo.ProviderName == doc.ProviderName) { //we found it cert = cert2; break; } } } } if (cert == null) { respo.HasError = true; respo.ErrorMessage = "Certifikata nuk u gjet!"; return(respo); } if (doc.PinCode != "") { //if pin code is set then no windows form will popup to ask it RSACryptoServiceProvider rsaForKeyContainer = (RSACryptoServiceProvider)cert.PrivateKey; SecureString pwd = GetSecurePin(doc.PinCode); CspParameters csp = new CspParameters(1, doc.ProviderName, rsaForKeyContainer.CspKeyContainerInfo.KeyContainerName, new System.Security.AccessControl.CryptoKeySecurity(), pwd); try { RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp); } catch (Exception ex) { respo.HasError = true; respo.ErrorMessage = "Crypto error: " + ex.Message; respo.StackTrace = ex.StackTrace; return(respo); } } //sign 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, "SHA-1"); PdfReader pdfReader; using (pdfReader = new PdfReader(doc.BasePdf)) { using (signedPdf_mem = new MemoryStream()) { pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf_mem, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; if (doc.SignImage != null && doc.SignImage.Length != 0) { signatureAppearance.SignatureGraphic = iTextSharp.text.Image.GetInstance(doc.SignImage); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; } else { signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION; } signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(100, 100, 250, 150), pdfReader.NumberOfPages, "NisaDigiSign"); signatureAppearance.Reason = "Certifikuar elektronikisht nga sistemi NISA"; ITSAClient TsaClient = new TSAClientBouncyCastle(doc.timestampServer); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, TsaClient, 0, CryptoStandard.CMS); respo.SignedPdf = signedPdf_mem.ToArray(); } } return(respo); }
private string PdfSign(byte[] signature, string certPath, string password, string name, string reason, iTextSharp.text.Rectangle signatureRect, int signaturePage, string fieldName, double dsvScore) { FileStream ksfs = null; Pkcs12Store pk12 = null; try { ksfs = new FileStream(certPath, FileMode.Open); pk12 = new Pkcs12Store(ksfs, password.ToCharArray()); string alias = ""; foreach (string al in pk12.Aliases) { if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate) { alias = al; break; } } Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry c in ce) { chain.Add(c.Certificate); } AsymmetricKeyEntry pk = pk12.GetKey(alias); RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters; string tmpFile = System.IO.Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0'); PdfContentByte cb = stamper.GetOverContent(signaturePage); Image integrityImage = Properties.Resources.integrity_red; if (dsvScore > Properties.Settings.Default.GreenThreshold) { integrityImage = Properties.Resources.integrity; } else if (dsvScore > Properties.Settings.Default.YellowThreshold) { integrityImage = Properties.Resources.integrity_yellow; } iTextSharp.text.Image imgIntegrity = iTextSharp.text.Image.GetInstance(integrityImage, ImageFormat.Png); imgIntegrity.SetAbsolutePosition(signatureRect.Left, signatureRect.Bottom - 20); imgIntegrity.ScalePercent(50.0f); cb.AddImage(imgIntegrity); iTextSharp.text.Image imgVerified = iTextSharp.text.Image.GetInstance(Properties.Resources.verified, ImageFormat.Png); imgVerified.SetAbsolutePosition(signatureRect.Left + 20, signatureRect.Bottom - 20); imgVerified.ScalePercent(50.0f); cb.AddImage(imgVerified); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; //uncomment this portion only //appearance.SignatureGraphic = iTextSharp.text.Image.GetInstance(signature); //appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; //appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(40, 110, 240, 210), 1, "Signature"); appearance.SetVisibleSignature(signatureRect, signaturePage, fieldName); //appearance.Certificate = chain[0]; to remain commented out /* * PdfTemplate n2 = appearance.GetLayer(2); * ColumnText ct = new ColumnText(n2); * ct.SetSimpleColumn(n2.BoundingBox); * string backgroundText = "Digitally signed by " + Properties.Settings.Default.DefaultName + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; * iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(backgroundText); * ct.AddElement(paragraph); * ct.Go(); */ string backgroundText = "Digitally signed by " + name + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; appearance.Layer2Text = backgroundText; appearance.Image = iTextSharp.text.Image.GetInstance(signature); //appearance.ImageScale = 1; IExternalSignature pks = new PrivateKeySignature((ICipherParameters)parameters, DigestAlgorithms.SHA256); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES); ksfs.Close(); //stamper.Close(); //fs.Close(); return(tmpFile); } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); } }
private void btnSign_Click(object sender, EventArgs e) { try { // Set wait cursor this.Cursor = Cursors.WaitCursor; Application.DoEvents(); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); // Get signature certificate for current citizen X509Certificate2Collection certsToShow = store.Certificates.Find(X509FindType.FindBySubjectName, "Assinatura", false); X509Certificate2Collection certs = certsToShow.Find(X509FindType.FindBySubjectName, "BI" + txtIdNumber.Text, false); if (certs.Count <= 0) { MessageBox.Show("Certificate not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var cert = certs[0]; if (cert != null) { // Sign every file found on listbox foreach (string file in lbFilesToSign.Items) { try { // Get source folder and source filename string sourceFolder = Path.GetDirectoryName(file); string filename = Path.GetFileName(file); lblStatus.Text = "A assinar o file " + filename; // Create "Signed" sub-folder if doesn't exists string signedFolder = Path.Combine(sourceFolder, "Signed"); if (!Directory.Exists(signedFolder)) { Directory.CreateDirectory(signedFolder); } // Generate destination path for signed file var signedFile = signedFolder + "/" + filename; // Convert X509Certificate2 to X509Certificate X509CertificateParser certParse = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certParse.ReadCertificate(cert.RawData) }; // Reader and stamper PdfReader pdfReader = new PdfReader(file); Stream signedPdf = new FileStream(signedFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, cbMultiSign.Checked); // Appearance PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SignatureCreator = "PDF Signer 1.0"; if (txtReason.Text != "") { appearance.Reason = txtReason.Text; } if (txtLocation.Text != "") { appearance.Location = txtLocation.Text; } // Timestamp TSAClientBouncyCastle tsc = null; if (cbSignWithTSA.Checked == true) { tsc = new TSAClientBouncyCastle("http://ts.cartaodecidadao.pt/tsa/server", "", ""); } // Digital signature X509Certificate2Signature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, tsc, 0, CryptoStandard.CMS); stamper.Close(); } catch (System.IO.IOException) { MessageBox.Show("File not found", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } // Remove all files from listbox lbFilesToSign.Items.Clear(); btnRemoveFile.Enabled = false; btnSignNow.Enabled = false; MessageBox.Show("You have successfully signed the document(s)", "Success!"); } else { MessageBox.Show("Certificate not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } catch (System.Security.Cryptography.CryptographicException) { } catch (System.Net.WebException) { MessageBox.Show("You must have an internet connection to use timestamp server.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } catch (Exception) { MessageBox.Show("Oops.. Something wrong.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { // Set default cursor this.Cursor = Cursors.Default; if (lblStatus.Text.Contains("A assinar o file")) { lblStatus.Text = "Card Inserted."; } } }
public void SignPdfDocument() { // Specify path to the unsigned PDF that will be created by this code string unsignedPdfPath = @"c:\temp\unsigned.pdf"; // Specify path to the signed PDF that will be created by this code string signedPdfPath = @"c:\temp\signed.pdf"; // Create simple PDF document with iText using (Document document = new Document(PageSize.A4, 50, 50, 50, 50)) { using (FileStream outputStream = new FileStream(unsignedPdfPath, FileMode.Create)) { using (PdfWriter pdfWriter = PdfWriter.GetInstance(document, outputStream)) { document.Open(); document.Add(new Paragraph("Hello World!")); document.Close(); } } } // Do something interesting with unsigned PDF document FileInfo unsignedPdfInfo = new FileInfo(unsignedPdfPath); Assert.IsTrue(unsignedPdfInfo.Length > 0); // Specify path to the unmanaged PCKS#11 library string libraryPath = @"siecap11.dll"; // Specify serial number of the token that contains signing key. May be null if tokenLabel is specified. string tokenSerial = null; // Specify label of of the token that contains signing key. May be null if tokenSerial is specified string tokenLabel = @"Pkcs11Interop"; // Specify PIN for the token string pin = @"11111111"; // Specify label (value of CKA_LABEL attribute) of the private key used for signing. May be null if ckaId is specified. string ckaLabel = @"John Doe"; // Specify hex encoded string with identifier (value of CKA_ID attribute) of the private key used for signing. May be null if ckaLabel is specified. string ckaId = null; // Specify hash algorihtm used for the signature creation HashAlgorithm hashAlgorithm = HashAlgorithm.SHA256; // Create instance of Pkcs11Signature class that allows iText to create PKCS#1 v1.5 RSA signature with the private key stored on PKCS#11 compatible device using (Pkcs11RsaSignature pkcs11RsaSignature = new Pkcs11RsaSignature(libraryPath, tokenSerial, tokenLabel, pin, ckaLabel, ckaId, hashAlgorithm)) { // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = pkcs11RsaSignature.GetSigningCertificate(); // All certificates stored on the token can be usually read with GetAllCertificates() method List <byte[]> otherCertificates = pkcs11RsaSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = CertUtils.BuildCertPath(signingCertificate, otherCertificates); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(unsignedPdfPath)) { // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(signedPdfPath, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0', Path.GetTempFileName(), true)) { // Sign PDF document MakeSignature.SignDetached(pdfStamper.SignatureAppearance, pkcs11RsaSignature, certPath, null, null, null, 0, CryptoStandard.CADES); } } } } // Do something interesting with the signed PDF document FileInfo signedPdfInfo = new FileInfo(signedPdfPath); Assert.IsTrue(signedPdfInfo.Length > signedPdfPath.Length); }
private int SignWithThisCert(X509Certificate2 Certificate, string Contact, string SourcePdfFileName, string DestPdfFileName) { try { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[1]; chain[0] = cp.ReadCertificate(Certificate.RawData); IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1"); PdfReader pdfReader = new PdfReader(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create); //the output pdf file PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfContentByte pdfData = pdfStamper.GetOverContent(1); /* * iTextSharp.text.Document d = new iTextSharp.text.Document(); * PdfWriter writer =PdfWriter.GetInstance(d,signedPdf); * d.Open(); * PdfContentByte cb = writer.DirectContent; * cb.BeginText(); * * cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ITALIC, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12); * cb.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, "Shreyas-Kalyanaraman", 300, 700, 0); * cb.ShowText("Shreyas Kalyanaraman"); * cb.EndText(); * d.Close(); * writer.Close(); */ //Create the QR Code/2D Code------------------------------- // Image qrImage = GenerateQRCode(Convert.ToBase64String(Certificate.RawData)); Image qrImage = GenerateQRCode(Contact); iTextSharp.text.Image itsQrCodeImage = iTextSharp.text.Image.GetInstance(qrImage, System.Drawing.Imaging.ImageFormat.Jpeg); itsQrCodeImage.SetAbsolutePosition(270, 50); pdfData.AddImage(itsQrCodeImage); //Create the QR Code/2D Code-------------------------------END PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.Acro6Layers = true; signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(33, 50, 270, 130), 1, null); //here set signatureAppearance at your will signatureAppearance.Contact = Contact; signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Stamp the PDF //MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES); // d.Close(); //writer.Close(); signedPdf.Close(); return(1); } catch (Exception ex) { if (!System.IO.File.Exists(SourcePdfFileName)) { ViewBag.Status = ex.Message; } Exception ex2 = new Exception(); ViewBag.Status = ex2.Message; throw ex2; } }
private static void CreateSignature(SigningCertificates signingCertificates, PdfSignatureAppearance signatureAppearance, ICollection <ICrlClient> clrClients, IOcspClient oscpClient) { IExternalSignature externalSignature = new X509Certificate2Signature(signingCertificates.X509Certificate2, "SHA-1"); MakeSignature.SignDetached(signatureAppearance, externalSignature, signingCertificates.FinalChain, clrClients, oscpClient, null, 0, CryptoStandard.CMS); }
static void Main(string[] args) { PdfReader pdfReaderLocal = null; FileStream fout = null; float RectRight = 0; float RectLeft = 0; float RectTop = 0; float RectBottom = 0; try { bool isVisibleSignature = true; int noOfPage = 0; bool iscert = false; X509Certificate2 mcert = null; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates; if (certificates.Count == 0) { store = new X509Store(StoreName.My, StoreLocation.LocalMachine); } foreach (X509Certificate2 certs in certificates) { if (certs.GetName().Contains("Exalca DS Ver2.0")) { iscert = true; mcert = certs; Console.WriteLine("found cert Exalca DS Ver2.0"); } } //string Internal_path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Signed_Doc") + "\\" + InvoiceName; string inptfldr = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputFldr"); if (!Directory.Exists(inptfldr)) { Directory.CreateDirectory(inptfldr); } string outfldr = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OutputFldr"); if (!Directory.Exists(outfldr)) { Directory.CreateDirectory(outfldr); } if (iscert) { string Sign_Location = "Bengaluru"; string Sign_AllPages = "N"; X509Certificate2 cert = mcert; //get certificate based on thumb print 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, "SHA1"); //PdfReader pdfReader = new PdfReader(sourceDocument); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); //ErrorLog.WriteHistoryLog("Open for write"); //signatureAppearance.SignatureGraphic = Image.GetInstance(pathToSignatureImage); //signatureAppearance.Reason = reason; signpdf method pdfReaderLocal = new PdfReader(inptfldr + "//s.pdf"); noOfPage = pdfReaderLocal.NumberOfPages; iTextSharp.text.Rectangle mediabox = pdfReaderLocal.GetPageSize(1); fout = new FileStream(outfldr + "\\123.pdf", FileMode.Append, FileAccess.Write); PdfStamper stamper = PdfStamper.CreateSignature(pdfReaderLocal, fout, '\0', null, true); PdfSignatureAppearance signatureAppearance = stamper.SignatureAppearance; signatureAppearance.ReasonCaption = ""; signatureAppearance.Reason = "Exalca"; signatureAppearance.LocationCaption = ""; signatureAppearance.Location = "Bengaluru"; signatureAppearance.Acro6Layers = false; signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark; BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); signatureAppearance.Layer2Font = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.NORMAL); var rec1 = new iTextSharp.text.Rectangle(610, 75, 440, 150); signatureAppearance.SetVisibleSignature(rec1, 1, "Signature" + 1); //i-->Page no,Signature1--->Field name MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (pdfReaderLocal != null) { pdfReaderLocal.Close(); pdfReaderLocal.Dispose(); } if (fout != null) { fout.Close(); fout.Dispose(); } } }
static int Main(string[] args) { if (args.Length == 0) { PrintUsage(); return((int)ExitCode.Success); } Arguments.Populate(); if (string.IsNullOrEmpty(SourceFile)) { PrintUsage(); return((int)ExitCode.NoInputFile); } if (string.IsNullOrEmpty(DestinationFile)) { PrintUsage(); return((int)ExitCode.NoOutputFile); } if (string.IsNullOrEmpty(Pincode)) { PrintUsage(); return((int)ExitCode.NoPin); } using (EidSignature eidSignature = new EidSignature(Pincode)) { if (eidSignature.ReadersCount == 0) { Console.WriteLine("No card reader connected"); return((int)ExitCode.NoCardReader); } if (eidSignature.IsCardInserted == false) { Console.WriteLine("No eid card inserted in the reader"); return((int)ExitCode.NoCardInserted); } // When signing certificate is stored on the token it can be usually read with GetSigningCertificate() method byte[] signingCertificate = eidSignature.GetSigningCertificate(); if (signingCertificate == null) { Console.WriteLine("No signing certificate found"); return((int)ExitCode.NoCertificate); } // All certificates stored on the token can be usually read with GetAllCertificates() method List <byte[]> otherCertificates = eidSignature.GetAllCertificates(); // Build certification path for the signing certificate ICollection <Org.BouncyCastle.X509.X509Certificate> certPath = eidSignature.BuildCertPath(signingCertificate, otherCertificates); TSAClientBouncyCastle tsaClient = new TSAClientBouncyCastle("http://tsa.belgium.be/connect"); // Read unsigned PDF document using (PdfReader pdfReader = new PdfReader(SourceFile)) { string tmpSigned = Path.GetTempFileName(); // Create output stream for signed PDF document using (FileStream outputStream = new FileStream(tmpSigned, FileMode.Create)) { // Create PdfStamper that applies extra content to the PDF document using (PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, outputStream, '\0')) { PdfSignatureAppearance appearance = pdfStamper.SignatureAppearance; List <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium2.crl")); crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium3.crl")); crlList.Add(new CrlClientOnline("http://crl.eid.belgium.be/belgium4.crl")); // Sign PDF document try { MakeSignature.SignDetached(appearance, eidSignature, certPath, crlList, null, tsaClient, 0, CryptoStandard.CADES); } catch (Exception e) { Console.WriteLine(e.Message); return((int)ExitCode.UnknownError); } } } try { AddLtv(tmpSigned, DestinationFile, null, new CrlClientOnline(), tsaClient); } catch (Exception e) { Console.WriteLine(e.Message); return((int)ExitCode.UnknownError); } } } return((int)ExitCode.Success); }
//PDF盖章 private bool PDFWatermark(string inputfilepath, string outputfilepath, X509Certificate2 cert) { string ModelPicName = textGZpath.Text; //印章文件路径 int zyz = comboYz.SelectedIndex; //加印章方式 int zqfz = comboQfz.SelectedIndex; //加骑缝章方式 int sftype = comboBoxBL.SelectedIndex; //印章缩放方式 float sfsize, qfzwzbl; float.TryParse(textBili.Text, out sfsize); //印章缩放尺寸 float.TryParse(textWzbl.Text, out qfzwzbl); //骑缝章位置比例 float picbl = 1.003f; //别问我这个数值怎么来的 float picmm = 2.842f; //别问我这个数值怎么来的 PdfGState state = new PdfGState(); state.FillOpacity = 0.6f;//印章图片整体透明度 //throw new NotImplementedException(); PdfReader pdfReader = null; PdfStamper pdfStamper = null; try { pdfReader = new PdfReader(inputfilepath);//选择需要印章的pdf if (comboQmtype.SelectedIndex != 0) { //最后的true表示保留原签名 pdfStamper = PdfStamper.CreateSignature(pdfReader, new FileStream(outputfilepath, FileMode.Create), '\0', null, true);//加完印章后的pdf } else { pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create)); } int numberOfPages = pdfReader.NumberOfPages;//pdf页数 PdfContentByte waterMarkContent; if (zqfz == 0 && numberOfPages > 1) { int max = 20;//骑缝章最大分割数 int ss = numberOfPages / max + 1; int sy = numberOfPages - ss * max / 2; int sys = sy / ss; int syy = sy % ss; int pp = max / 2 + sys; Bitmap[] nImage; int startpage = 0; for (int i = 0; i < ss; i++) { int tmp = pp; if (i < syy) { tmp++; } nImage = subImages(ModelPicName, tmp); for (int x = 1; x <= tmp; x++) { int page = startpage + x; waterMarkContent = pdfStamper.GetOverContent(page); //获取当前页内容 int rotation = pdfReader.GetPageRotation(page); //获取当前页的旋转度 iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(page); //获取当前页尺寸 iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(nImage[x - 1], System.Drawing.Imaging.ImageFormat.Bmp); //获取骑缝章对应页的部分 image.Transparency = new int[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //这里透明背景的图片会变黑色,所以设置黑色为透明 waterMarkContent.SaveState(); //通过PdfGState调整图片整体的透明度 waterMarkContent.SetGState(state); //image.GrayFill = 20;//透明度,灰色填充 //image.Rotation//旋转 //image.ScaleToFit(140F, 320F);//设置图片的指定大小 //image.RotationDegrees//旋转角度 float sfbl, imageW, imageH; if (sftype == 0) { sfbl = sfsize * picbl;//别问我为什么要乘这个 imageW = image.Width * sfbl / 100f; imageH = image.Height * sfbl / 100f; //image.ScalePercent(sfbl);//设置图片比例 image.ScaleToFit(imageW, imageH);//设置图片的指定大小 } else { sfbl = sfsize * picmm;//别问我为什么要乘这个 imageW = sfbl / tmp; imageH = sfbl; image.ScaleToFit(imageW, imageH);//设置图片的指定大小 } //水印的位置 float xPos, yPos; if (rotation == 90 || rotation == 270) { xPos = psize.Height - imageW; yPos = (psize.Width - imageH) * (100 - qfzwzbl) / 100; } else { xPos = psize.Width - imageW; yPos = (psize.Height - imageH) * (100 - qfzwzbl) / 100; } image.SetAbsolutePosition(xPos, yPos); waterMarkContent.AddImage(image); waterMarkContent.RestoreState(); } startpage += tmp; } } if (zyz != 0 || comboQmtype.SelectedIndex != 0) { iTextSharp.text.Image img = null; float sfbl, imgW = 0, imgH = 0; float xPos = 0, yPos = 0; bool all = false; int signpage = 0; if (zyz != 0) { img = iTextSharp.text.Image.GetInstance(ModelPicName); //创建一个图片对象 img.Transparency = new int[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //这里透明背景的图片会变黑色,所以设置黑色为透明 if (sftype == 0) { sfbl = sfsize * picbl;//别问我为什么要乘这个 imgW = img.Width * sfbl / 100f; imgH = img.Height * sfbl / 100f; //img.ScalePercent(sfbl);//设置图片比例 img.ScaleToFit(imgW, imgH);//设置图片的指定大小 } else { sfbl = sfsize * picmm;//别问我为什么要乘这个 imgW = sfbl; imgH = sfbl * img.Height / img.Width; img.ScaleToFit(imgW, imgH);//设置图片的指定大小,实际只能指定宽度,高度还是按照图片比例计算的 } } if (zyz == 1) { signpage = numberOfPages; } else if (zyz == 2) { signpage = 1; } else if (zyz == 3) { signpage = numberOfPages; all = true; } for (int i = 1; i <= numberOfPages; i++) { if (all || i == signpage) { waterMarkContent = pdfStamper.GetOverContent(i); //获取当前页内容 int rotation = pdfReader.GetPageRotation(i); //获取指定页面的旋转度 iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(i); //获取当前页尺寸 waterMarkContent.SaveState(); //通过PdfGState调整图片整体的透明度 waterMarkContent.SetGState(state); float wbl = 0; float hbl = 1; DataRow[] arrRow = dtPos.Select("Path = '" + inputfilepath + "' and Page = " + i); if (arrRow == null || arrRow.Length == 0) { wbl = Convert.ToSingle(textPx.Text); //这里根据比例来定位 hbl = 1 - Convert.ToSingle(textPy.Text); //这里根据比例来定位 } else { DataRow dr = arrRow[0]; wbl = Convert.ToSingle(dr["X"].ToString()); hbl = 1 - Convert.ToSingle(dr["Y"].ToString()); } if (rotation == 90 || rotation == 270) { xPos = (psize.Height - imgW) * wbl; yPos = (psize.Width - imgH) * hbl; } else { xPos = (psize.Width - imgW) * wbl; yPos = (psize.Height - imgH) * hbl; } img.SetAbsolutePosition(xPos, yPos); waterMarkContent.AddImage(img); waterMarkContent.RestoreState(); //普通印章跟数字印章已经完美重叠,所以就不需要通过以下方法特殊区分了 //同时启用印章和数字签名的话用最后一个印章用数字签名代替 //if (all) //{ // if (comboQmtype.SelectedIndex == 0) // { // //所有页要盖章,并且不是数字签名 // waterMarkContent.AddImage(img); // waterMarkContent.RestoreState(); // } // else if (i != numberOfPages) // { // //所有页要盖章,要数字签名,但是不是最后一页 // waterMarkContent.AddImage(img); // waterMarkContent.RestoreState(); // } //} //else if (comboQmtype.SelectedIndex == 0) //{ // //只有首页或尾页要盖章,并且不是数字签名 // waterMarkContent.AddImage(img); // waterMarkContent.RestoreState(); //} ////开始增加文本 //waterMarkContent.BeginText(); //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); ////设置字体 大小 //waterMarkContent.SetFontAndSize(bf, 9); ////指定添加文字的绝对位置 //waterMarkContent.SetTextMatrix(imgLeft, 200); ////增加文本 //waterMarkContent.ShowText("GW INDUSTRIAL LTD"); ////结束 //waterMarkContent.EndText(); //如果不是所有页都盖章,那对应页盖完后直接跳出循环 if (!all && i == signpage) { break; } } } //加数字签名 if (comboQmtype.SelectedIndex != 0) { Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) }; Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(cert.GetRSAPrivateKey()); IExternalSignature externalSignature = new PrivateKeySignature(pk.Private, DigestAlgorithms.SHA256); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; signatureAppearance.SignDate = DateTime.Now; //signatureAppearance.SignatureCreator = ""; //signatureAppearance.Reason = "验证身份"; //signatureAppearance.Location = "深圳"; if (zyz == 0) { signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(0, 0, 0, 0), numberOfPages, null); } else { signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC; //仅体现图片 signatureAppearance.SignatureGraphic = img; //iTextSharp.text.Image.GetInstance(ModelPicName); //signatureAppearance.Acro6Layers = true; //StringBuilder buf = new StringBuilder(); //buf.Append("Digitally Signed by "); //String name = cert.SubjectName.Name; //buf.Append(name).Append('\n'); //buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz")); //string text = buf.ToString(); //signatureAppearance.Layer2Text = text; float bk = 2;//数字签名的图片要加上边框才能跟普通印章的位置完全一致 signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPos - bk, yPos - bk, xPos + imgW + bk, yPos + imgH + bk), signpage, "Signature"); } MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); } } return(true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } finally { if (pdfStamper != null) { pdfStamper.Close(); } if (pdfReader != null) { pdfReader.Close(); } } }
public void Sign(SingInfo singInfo) { try { var metaData = new MetaData { Author = singInfo.Author, Title = singInfo.Title, Subject = singInfo.Subject, Keywords = singInfo.Keywords, Creator = singInfo.Creator, Producer = singInfo.Producer }; var store = new X509Store(StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); if (store.Certificates.Count == 0) { Log.Application.Error("Certificados Locais do usuario indisponiveis."); } var posicaoCertificado = 0; var cert = store.Certificates[posicaoCertificado]; Log.Application.InfoFormat( "Certificado Selecionado {0} Serial {1} Subject {2}", cert.IssuerName.Name, cert.SerialNumber, cert.SubjectName); var cp = new Org.BouncyCastle.X509.X509CertificateParser(); var chain = new[] { cp.ReadCertificate(cert.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(cert, "SHA-1"); var rsa = (RSACryptoServiceProvider)cert.PrivateKey; var secureString = new SecureString(); secureString.AppendChar(char.Parse("1")); secureString.AppendChar(char.Parse("2")); secureString.AppendChar(char.Parse("3")); secureString.AppendChar(char.Parse("4")); var cspp = new CspParameters(); cspp.KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName; cspp.ProviderName = rsa.CspKeyContainerInfo.ProviderName; cspp.Flags = CspProviderFlags.UseUserProtectedKey; cspp.KeyPassword = secureString; cspp.ProviderType = rsa.CspKeyContainerInfo.ProviderType; cspp.Flags = CspProviderFlags.NoPrompt; RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider(cspp); rsa.PersistKeyInCsp = true; PdfReader reader = new PdfReader(singInfo.SourcePdf); PdfAStamper stamper = PdfAStamper.CreateSignature( reader, new FileStream(singInfo.TargetPdf, FileMode.Create, FileAccess.Write), '\0', PdfAConformanceLevel.PDF_A_2A); PdfSignatureAppearance appearance = stamper.SignatureAppearance; var caminhoFonte2 = @"C:\Windows\Fonts\cour.ttf"; var caminhoGrafico = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "key.jpg"); appearance.Layer2Font = FontFactory.GetFont(caminhoFonte2, BaseFont.WINANSI, BaseFont.EMBEDDED, 8); appearance.Reason = singInfo.SignatureReason; appearance.Contact = singInfo.SignatureContact; appearance.Location = singInfo.SignatureLocation; appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(600, 100, 0, 0), 1, "Assinatura"); MakeSignature.SignDetached(appearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); stamper.Close(); } catch (Exception exception) { Log.Application.Error("Falha ao assinar! ", exception); throw; } }
/// <summary> /// Signs a PDF document using iTextSharp library /// </summary> /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param> /// <param name="destinationDocument">The path at which the signed pdf document should be generated</param> /// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param> /// <param name="pfxKeyPass">The password for the private key</param> /// <param name="reasonForSigning">String describing the reason for signing, would be embedded as part of the signature</param> /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param> public void SignPdfFile(string sourceDocument, string destinationDocument, PdfSignInfo info) { using (var cpfxFile = new FileStream(info.pfxFilePath, FileMode.Open, FileAccess.Read)) { Pkcs12Store pk12 = new Pkcs12Store(cpfxFile, info.pfxKeyPass.ToCharArray()); string alias = null; foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; using (var reader = new PdfReader(sourceDocument)) using (var fout = new FileStream(destinationDocument, FileMode.Create, FileAccess.ReadWrite)) using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { if (info.DocPass != null) { stamper.SetEncryption(info.DocPass, info.DocPass, PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH128BITS); } var img = new iTextSharp.text.Jpeg(new Uri(info.SignImagePath)); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Image = img; appearance.Reason = info.ReasonForSigning; appearance.Location = info.Location; const float x = 20, y = 10; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + img.Width, y + img.Width), 1, "Icsi-Vendor"); IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); //http://www.phronesisweb.com/blog/filling-pdf-acrofields-in-c-using-itextsharp/ AcroFields form = stamper.AcroFields; form.GenerateAppearances = true; ////form.SetField("name", "John Doe"); ////form.SetField("address", "xxxxx, yyyy"); ////form.SetField("postal_code", "12345"); ////form.SetField("email", "*****@*****.**"); if (info.MetaData != null) { lock (info.MetaData) { foreach (Tuple <string, string> kv in info.MetaData) { form.SetField(kv.Item1, kv.Item2); //form.SetFieldProperty(kv.Item1.Compress(), "fflags", 0, null); } } } //http://forums.asp.net/t/1846462.aspx?PDF+form+contents+are+not+visible+iTextSharp //Dictionary<string, string> inf = reader.Info; ////inf.Add("Title", "Hello World stamped"); ////inf.Add("Subject", "Hello World with changed metadata"); ////inf.Add("Keywords", "iText in Action, PdfStamper"); ////inf.Add("Creator", "Silly standalone example"); ////inf.Add("Author", "Also Bruno Lowagie"); //if (info.MetaData != null) //{ // lock (info.MetaData) // foreach (Tuple<string, string> kv in info.MetaData) // inf.Add(kv.Item1, kv.Item2); // stamper.MoreInfo = inf; //} //stamper.SetFullCompression(); //stamper.Writer.SetFullCompression(); stamper.FormFlattening = true; stamper.Close(); } } }
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 { } }
// 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); } }
//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 byte[] signPdf(byte[] inputPdf, byte[] sigImg, string signatureField) { this.getCRLList(); Console.WriteLine("Read PDF"); PdfReader reader = new PdfReader(inputPdf); MemoryStream output = new MemoryStream(); PdfStamper stamper = PdfStamper.CreateSignature(reader, output, '\0', null, true); PdfSignatureAppearance sap = stamper.SignatureAppearance; sap.Reason = "test"; sap.Location = "Bangkok"; // Set Signature Image if (sigImg != null) { sap.SignatureGraphic = Image.GetInstance(sigImg); sap.ImageScale = -1; sap.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC; } // Set Signature Field if (signatureField.Equals("") || signatureField == null) { Rectangle location = new Rectangle(10, 10, 300, 100); sap.SetVisibleSignature(location, 1, "signatureField"); } else { sap.SetVisibleSignature(signatureField); } sap.CertificationLevel = PdfSignatureAppearance.NOT_CERTIFIED; //Create TSA server ITSAClient tsaClient = null; Boolean isTsaConnected = false; if (tsa) { tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUsername, tsaPassword); for (int retry = 0; retry < 5; retry++) { try { //int hash = tsaClient.GetHashCode(); string testString = "test"; byte[] digest; using (SHA256Managed sha256 = new SHA256Managed()) { digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(testString)); } tsaClient.GetTimeStampToken(digest); isTsaConnected = true; break; } catch (Exception e) { Console.WriteLine(e.StackTrace); } Console.WriteLine("retry " + (retry + 1)); } } //Do Signing Check not null timestamp and crl if (tsaClient != null && crlList != null && isTsaConnected) { try { MakeSignature.SignDetached(sap, this.signature, chain, this.crlList, null, tsaClient, 0, CryptoStandard.CADES); } catch (Exception e) { Console.WriteLine(e.StackTrace); } } else { Console.WriteLine("Cannot sign the PDF file."); return(null); } reader.Close(); stamper.Close(); signature = null; return(output.ToArray()); }
public static byte[] AssinarPdf(X509Certificate2 certificate, DadosAssinatura dadosAssinatura) { try { // ler arquivo e insere dados de assinatura using (PdfReader reader = new PdfReader(dadosAssinatura.ArquivoPdf)) { using (MemoryStream fout = new MemoryStream()) { PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'); // texto marca d'água Font f = new Font(Font.FontFamily.UNDEFINED, 10); Phrase pAssinado = new Phrase("Assinado digitalmente por:", f); string[] dados = certificate.GetNameInfo(X509NameType.SimpleName, false).Split(':'); Phrase pNome = new Phrase(dados[0], f); Phrase pDocumento = new Phrase(dados[1], f); Phrase pData = new Phrase(certificate.GetEffectiveDateString(), f); Phrase pServico = new Phrase(dadosAssinatura.Servico, f); // Imagem marca d'água Image img = dadosAssinatura.Imagem; float w = 200F; float h = 75.2F; // Transparência PdfGState gs1 = new PdfGState(); // Propriedades PdfContentByte over; Rectangle pagesize; int n = reader.NumberOfPages; //Página var pagina = 1; pagesize = reader.GetPageSizeWithRotation(pagina); switch (dadosAssinatura.PaginaAssinatura) { case EnumPaginaAssinatura.PRIMEIRA: pagina = 1; break; case EnumPaginaAssinatura.ULTIMA: pagina = reader.NumberOfPages; break; default: pagina = 1; break; } float x, y, xr = 0, hr = 0, yr = 0, wr = 0; //Posição da assinatura switch (dadosAssinatura.Posicao) { case EnumPosicao.ACIMA_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 0.5F; wr = w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ACIMA_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Top * 0.88); xr = pagesize.Right * 0.97F; wr = xr - w; yr = pagesize.Top * 0.97F; hr = pagesize.Top * 0.88F; break; case EnumPosicao.ABAIXO_ESQUERDA: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Bottom * 0.88); xr = x * 0.5F; wr = w; yr = y; hr = h; break; case EnumPosicao.ABAIXO_DIREITA: x = (float)(pagesize.Right * 0.64); y = (float)(pagesize.Bottom * 0.88); xr = x * 1.53F; wr = w * 1.9F; yr = y; hr = h; break; default: x = (float)(pagesize.Left * 0.88); y = (float)(pagesize.Top * 0.88); xr = x * 1.53F; wr = w * 1.9F; break; } //Plota a assinatura no pdf over = stamper.GetOverContent(pagina); over.SaveState(); over.SetGState(gs1); over.AddImage(img, w, 0, 0, h, x, y); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pAssinado, x + 10, y + 60, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pNome, x + 10, y + 50, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pDocumento, x + 10, y + 40, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pData, x + 10, y + 25, 0); ColumnText.ShowTextAligned(over, Element.ALIGN_TOP, pServico, x + 10, y + 10, 0); over.RestoreState(); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; appearance.Layer2Text = ""; appearance.Layer4Text = ""; Rectangle rect = new Rectangle(wr, hr, xr, yr); appearance.SetVisibleSignature(rect, pagina, "Assinatura Digital"); ICollection <Org.BouncyCastle.X509.X509Certificate> certChain; IExternalSignature es = ResolveExternalSignatureFromCertStore(certificate, dadosAssinatura.CertificadoValido, out certChain); //Autenticação da assinatura digital MakeSignature.SignDetached(appearance, es, certChain, null, null, null, 0, CryptoStandard.CADES); stamper.Close(); return(fout.ToArray()); } } } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Erro durante assinatura digital do pdf: {0}", ex.Message); throw; } }
private void sign(X509Certificate2 cert, String imput, String output, int posicaoAssinatura) { string SourcePdfFileName = imput; string DestPdfFileName = output; string requerente = ""; 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, "SHA-1"); PdfReader pdfReader = new PdfReader(SourcePdfFileName); FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create); //the output pdf file PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance; requerente = cert.Subject.Replace("CN=", "").Replace("OU=", "").Replace("DC=", "").Replace("O=", "").Replace("C=", ""); //ajusta a posição da assinatura float alturaPagina = pdfReader.GetPageSize(1).Height; float larguraPagina = pdfReader.GetPageSize(1).Right; int[] coordenadasAssinatura = new int[4]; Rectangle rectangle = new Rectangle(0, 0, 0, 0); switch (posicaoAssinatura) { case 1: rectangle = new Rectangle(0, alturaPagina - 5, larguraPagina / 3, alturaPagina - 55); break; case 2: rectangle = new Rectangle(larguraPagina / 3, alturaPagina - 5, larguraPagina / 3 * 2, alturaPagina - 55); break; case 3: rectangle = new Rectangle(larguraPagina / 3 * 2, alturaPagina - 5, larguraPagina, alturaPagina - 55); break; case 4: rectangle = new Rectangle(0, 10, larguraPagina / 3, 60); break; case 5: rectangle = new Rectangle(larguraPagina / 3, 10, larguraPagina / 3 * 2, 60); break; case 6: //rectangle = new Rectangle(350, 30, 550, 80); rectangle = new Rectangle(larguraPagina / 3 * 2, 10, larguraPagina, 60); break; } signatureAppearance.SetVisibleSignature(rectangle, 1, "Signature"); signatureAppearance.Layer2Text = "Assinado de forma digital por " + requerente + Environment.NewLine + "Dados:" + DateTime.Now; //string pathImage = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "assinatura.png"); //var image = iTextSharp.text.Image.GetInstance(pathImage); //signatureAppearance.Image = iTextSharp.text.Image.GetInstance(pathImage); //signatureAppearance.ImageScale = 0.5F; //signatureAppearance.Image.Alignment = Element.ALIGN_JUSTIFIED; signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION; MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS); }