public static void AddTextSignature2PDF() { //Please repace the trial key from trial-license.txt in download package //This license registration line need to be at very beginning of our other code LicenseManager.SetKey("trial key"); //Input your certificate and password PdfCertificate cert = new PdfCertificate("test.pfx", "iditect"); PdfSigner signer = new PdfSigner("sample.pdf", cert); //Set signature information signer.SignatureInfo.Contact = "123456789"; signer.SignatureInfo.Reason = "Sign by iDiTect"; signer.SignatureInfo.Location = "World Wide Web"; //Field name need to be unique in the same pdf document signer.SignatureInfo.FieldName = "iDiTect Sign Field"; //Sign in target page signer.SignatureInfo.PageId = 0; //Sign in target area signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50); signer.SignatureAlgorithm = SignatureAlgorithm.SHA256; signer.SignatureType = SignatureType.Text; signer.Sign("signed.pdf"); }
public void SignDocument() { string outputPdfName = String.Format("{0}.pdf", DateTime.Now.ToString("s").Replace(":", "-")); this._outputPdf = Path.Combine(_documentDir, outputPdfName); Cert cert = null; try { PdfSignatureAp sigAp = new PdfSignatureAp(); sigAp.Visible = false; sigAp.Multi = MultiSignature.Checked; sigAp.Page = 0; //sigAp.SigContact = "*****@*****.**"; if (_certificateData.HasPrivateKey) { var password = String.IsNullOrWhiteSpace(passwordBox.Text) ? Guid.NewGuid().ToString("N") : passwordBox.Text; byte[] bytes = _certificateData.Export(X509ContentType.Pfx, password); cert = new Cert(bytes, password); } PdfSigner pdfSigner = new PdfSigner(_inputPdf, this._outputPdf, cert); pdfSigner.Sign(sigAp); } catch (Exception ex) { DokuFlex.Windows.Common.Log.LogFactory.CreateLog().LogError(ex); MessageBox.Show(String.Format("{0}\nError:{1}", ErrorMessages.OpenCertificateError, ex.Message), "DokuSign"); throw ex; } try { _documentId = _pdfReader.GetDocumentTagValue("Document ID:", 33); } catch (Exception ex) { DokuFlex.Windows.Common.Log.LogFactory.CreateLog().LogError(ex); MessageBox.Show(ErrorMessages.ApplicationError); throw ex; } ConfigurationManager.SetValue(Constants.LocalCertificate, certificateList.SelectedIndex.ToString()); ConfigurationManager.Save(); }
public static void AddImageSignature2PDF() { //Input your certificate and password PdfCertificate cert = new PdfCertificate("test.pfx", "iditect"); PdfSigner signer = new PdfSigner("sample.pdf", cert); //Support commonly used image format, like jpg, png, gif signer.SignatureImageFile = "sample.jpg"; //Field name need to be unique in the same pdf document signer.SignatureInfo.FieldName = "iDiTect Sign"; //Sign in target page signer.SignatureInfo.PageId = 0; //Sign in target area signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50); signer.SignatureAlgorithm = SignatureAlgorithm.SHA256; signer.SignatureType = SignatureType.Image; signer.Sign("signed.pdf"); }
public static void AddTextSignature2PDF() { //Input your certificate and password PdfCertificate cert = new PdfCertificate("test.pfx", "iditect"); PdfSigner signer = new PdfSigner("sample.pdf", cert); //Set signature information signer.SignatureInfo.Contact = "123456789"; signer.SignatureInfo.Reason = "Sign by iDiTect"; signer.SignatureInfo.Location = "World Wide Web"; //Field name need to be unique in the same pdf document signer.SignatureInfo.FieldName = "iDiTect Sign Field"; //Sign in target page signer.SignatureInfo.PageId = 0; //Sign in target area signer.SignatureInfo.Rect = new Rectangle(50, 100, 150, 50); signer.SignatureAlgorithm = SignatureAlgorithm.SHA256; signer.SignatureType = SignatureType.Text; signer.Sign("signed.pdf"); }
public static void AddImageSignature2PDF() { //Please repace the trial key from trial-license.txt in download package //This license registration line need to be at very beginning of our other code LicenseManager.SetKey("trial key"); //Input your certificate and password PdfCertificate cert = new PdfCertificate("test.pfx", "iditect"); PdfSigner signer = new PdfSigner("sample.pdf", cert); //Support commonly used image format, like jpg, png, gif signer.SignatureImageFile = "sample.jpg"; //Field name need to be unique in the same pdf document signer.SignatureInfo.FieldName = "iDiTect Sign"; //Sign in target page signer.SignatureInfo.PageId = 0; //Sign in target area signer.SignatureInfo.Rect = new Rectangle(50, 100, 100, 50); signer.SignatureAlgorithm = SignatureAlgorithm.SHA256; signer.SignatureType = SignatureType.Image; signer.Sign("signed.pdf"); }
private void kysoPDF() { List <string> duongdan = new List <string>(); this.Invoke(new Action(() => { tongsotaptin = lstDanhSachTepCanKySo.Items.Count; this.progressBar1.Maximum = tongsotaptin; })); for (int i = 0; i < tongsotaptin; i++) { this.Invoke(new Action(() => duongdan.Add(lstDanhSachTepCanKySo.Items[i].ToString()))); } bool TestSign = true; string input = ""; string output = ""; X509Certificate2Collection keyStore = new X509Certificate2Collection(); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); keyStore.AddRange(store.Certificates); store.Close(); //Chung thu so nguoi ky X509Certificate2 cert = null; //[1] Chon chung thu so Console.WriteLine("Chon chung thu so ky"); try { cert = X509Certificate2UI.SelectFromCollection(keyStore, "Chứng thư số ký", "Chọn chứng thư số ký", X509SelectionFlag.SingleSelection)[0]; Console.WriteLine(cert.Subject); } catch { } if (cert == null) { Console.WriteLine("Chua chon chung thu so ky"); return; } int dangxulytaptin = 0; int duongdanXuLy = 0; foreach (var item in duongdan) { dangxulytaptin = duongdanXuLy + 1; string xulyfileExcelthu = dangxulytaptin + "/" + tongsotaptin; this.Invoke(new Action(() => { progressBar1.Value = dangxulytaptin; lstDanhSachTepCanKySo.SelectedIndex = lstDanhSachTepCanKySo.FindString(item); lblTienTrinhXuLy.Text = xulyfileExcelthu; })); var path1 = Path.GetDirectoryName(item); var path = linkThuMucKetQuaKy.Text + path1.Replace(linkThuMucKy.Text, ""); new System.IO.DirectoryInfo(path).Create(); input = item; output = item.Replace(linkThuMucKy.Text, linkThuMucKetQuaKy.Text); if (TestSign) { //[3] Ky so PdfSigner pdf = new PdfSigner(input, output, cert); pdf.Location = txtDiaDiem.Text.Trim(); //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.GRAPHIC; //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả và hình ảnh //pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; //Image i = Image.FromFile("dau.jpg"); //pdf.SignatureImage = i; pdf.TsaUrl = "http://ca.gov.vn/tsa"; try { pdf.Sign( Convert.ToInt32(txtTrangHienThiChuKy.Text), Convert.ToInt32(txtToaDoX.Text), Convert.ToInt32(txtToaDoY.Text), Convert.ToInt32(txtChieuRongChuKy.Text), Convert.ToInt32(txtChieuCaoChuKy.Text), 0); //iPage: trang; llx: toa do X, lly: Toa do y; iWidth: rong; iHeight: cao Console.WriteLine("Ky so thanh cong!"); } catch (Exception ex) { Console.WriteLine("Loi: " + ex.Message); MessageBox.Show(ex.InnerException.ToString()); throw; } } } }
static void TestSignAndVerifyPDF() { bool TestSign = true; bool TestVerify = true; string input = @"test1.pdf"; string output = @"test1.signed.pdf"; if (TestSign) { X509Certificate2Collection keyStore = new X509Certificate2Collection(); X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); keyStore.AddRange(store.Certificates); store.Close(); //Chung thu so nguoi ky X509Certificate2 cert = null; //[1] Chon chung thu so Console.WriteLine("Chon chung thu so ky"); try { cert = X509Certificate2UI.SelectFromCollection(keyStore, "Chứng thư số ký", "Chọn chứng thư số ký", X509SelectionFlag.SingleSelection)[0]; Console.WriteLine(cert.Subject); } catch { } if (cert == null) { Console.WriteLine("Chua chon chung thu so ky"); return; } //[3] Ky so PdfSigner pdf = new PdfSigner(input, output, cert); pdf.Location = "Hà Nội"; //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.DESCRIPTION; //Hiển thị chữ ký trên tài liệu dạng thông tin miêu tả và hình ảnh //pdf.SignatureAppearance = PdfSignatureAppearance.RenderingMode.GraphicAndDescription; //pdf.SignatureImage = (Bitmap)image; pdf.TsaUrl = "http://ca.gov.vn/tsa"; try { pdf.Sign(1, 0, 0, 250, 50, 0); //iPage: trang; llx: toa do X, lly: Toa do y; iWidth: rong; iHeight: cao Console.WriteLine("Ky so thanh cong!"); } catch (Exception ex) { Console.WriteLine("Loi: " + ex.Message); return; } } if (TestVerify) { //[4] Xac thuc PdfVerifier verifier = new PdfVerifier(output); verifier.AllowedOnlineChecking = true; List <SignatureInfo> list = verifier.Verify(); if (list.Count <= 0) { Console.WriteLine("Van ban chua duoc ky so!"); } else { foreach (SignatureInfo info in list) { string str = string.Empty; string str2 = string.Empty; CertInfo info2 = null; bool flag = false; bool flag2 = false; try { info2 = new CertInfo(info.SigningCertificate); str = info2.ToString(); } catch { str = "N/A"; } string str3 = string.Format("{0}: Ky boi {1}", info.SignatureName, str); Console.WriteLine(str3); Console.WriteLine("- Tinh trang xac thuc:"); if (!info.ValidityErrors.ContainsKey(SignatureValidity.DocumentModified)) { Console.WriteLine("-- Tai lieu chua bi thay doi."); } else { Console.WriteLine("-- Tai lieu da bi thay doi."); flag = true; } if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidSigningCertificate)) { Console.WriteLine("-- Chung thu so khong hop le: " + info.ValidityErrors[SignatureValidity.InvalidSigningCertificate]); flag = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.ErrorCheckingSigningCertificate)) { Console.WriteLine("-- Loi kiem tra chung thu so: " + info.ValidityErrors[SignatureValidity.ErrorCheckingSigningCertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.NonCheckingRevokedSigningCert)) { Console.WriteLine("-- Chung thu so khong duoc kiem tra trang thai truc tuyen."); flag2 = true; } else { Console.WriteLine("-- Chung thu so hop le."); } if (info.ValidityErrors.ContainsKey(SignatureValidity.NotTimestamped)) { Console.WriteLine("-- Chu ky khong duoc gan dau thoi gian tin cay."); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidTimestampImprint)) { Console.WriteLine("-- Dau thoi gian khong hop le."); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.InvalidTSACertificate)) { Console.WriteLine("-- Chung thu so TSA khong hop le:" + info.ValidityErrors[SignatureValidity.InvalidTSACertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.ErrorCheckingTSACertificate)) { Console.WriteLine("-- Loi kiem tra chung thu so TSA: " + info.ValidityErrors[SignatureValidity.ErrorCheckingTSACertificate]); flag2 = true; } else if (info.ValidityErrors.ContainsKey(SignatureValidity.NonCheckingRevokedTSACert)) { Console.WriteLine("--Chung thu so TSA khong duoc kiem tra trang thai truc tuyen."); flag2 = true; } else { Console.WriteLine("-- Dau thoi gian hop le."); } if (!flag && !flag2) { Console.WriteLine("==> Chu ky hop le!"); } else if (flag) { Console.WriteLine("==> Chu ky khong hop le!"); } else { Console.WriteLine("==> Khong du thong tin xac thuc!"); } Console.WriteLine("--Thong tin chu ky"); if (!info.IsTsp) { try { str2 = info.SigningTime.ToString("dd/MM/yyyy HH:mm:ss zzz"); } catch { str2 = "N/A"; } Console.WriteLine(string.Format("--- Thoi gian ky: {0}", str2)); } else { Console.WriteLine("--- Chu ky la dau thoi gian"); } if (!info.ValidityErrors.ContainsKey(SignatureValidity.NotTimestamped)) { Console.WriteLine("--Thong tin dau thoi gian"); try { str2 = info.TimeStampDate.ToString("dd/MM/yyyy HH:mm:ss zzz"); } catch { str2 = "N/A"; } Console.WriteLine(string.Format("--- Gia tri dau thoi gian: {0}", str2)); if (!info.IsTsp) { try { str = new CertInfo(info.TimeStampCertificate).ToString(); } catch { str = "N/A"; } Console.WriteLine(string.Format("--- Chung thu so TSA: {0}", str)); } } try { Console.WriteLine(string.Format("--- Chu ky tren trang {0}", info.PageIndex.ToString())); continue; } catch { continue; } } } } Console.ReadLine(); }
private void FirmarFacturaToolStripMenuItemClick(object sender, EventArgs e) { using (OpenFileDialog openCertificadoFileDialog = new OpenFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal), Title = FacturasRecursos.Form1_firmarFacturaToolStripMenuItem_Click_Seleccione_su_certificado_de_usuario, Filter = FacturasRecursos.Form1_firmarFacturaToolStripMenuItem_Click_Certificado_Digital____p12____p12 }) { if (openCertificadoFileDialog.ShowDialog(this) == DialogResult.OK) { if (!string.IsNullOrEmpty(openCertificadoFileDialog.FileName)) { Passs pass = new Passs(); if (pass.ShowDialog() == DialogResult.OK) { Cert myCert = null; try { myCert = new Cert(openCertificadoFileDialog.FileName, pass.Password); } catch (Exception ex) { XtraMessageBox.Show(ex.Message, Application.ProductName); return; } OpenFileDialog openFileDialog = new OpenFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal), Title = FacturasRecursos. Form1_firmarFacturaToolStripMenuItem_Click_Seleccione_una_factura_sin_firmar, Filter = FacturasRecursos. Form1_firmarFacturaToolStripMenuItem_Click_Factura____pdf____pdf }; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { if (!string.IsNullOrEmpty(openFileDialog.FileName)) { MetaData myMd = new MetaData(); myMd.Author = Settings.Default.nombre; myMd.Title = string.Format("Factura emitida por {0}", Settings.Default.nombre); myMd.Subject = "Factura por translado en taxi"; myMd.Keywords = "factura, taxi, mariano"; myMd.Creator = "Riccardo Prieto Mendoza"; myMd.Producer = "Riccardo Prieto Mendoza"; using (SaveFileDialog sabeD = new SaveFileDialog { InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal), Title = FacturasRecursos.Form1_firmarFacturaToolStripMenuItem_Click_Guardar_Factura_Firmada_como___, Filter = FacturasRecursos.Form1_firmarFacturaToolStripMenuItem_Click_Factura____pdf____pdf }) { if (sabeD.ShowDialog(this) == DialogResult.OK) { PdfSigner pdfs = new PdfSigner(openFileDialog.FileName, sabeD.FileName, myCert, myMd); pdfs.Sign("Factura por translado en taxi", Settings.Default.email, Settings.Default.direccion + " " + Settings.Default.poblacionCP, false); Process.Start(sabeD.FileName); } } } } } } } } }