public int SignaturesCount(string filePath) { PdfReader Reader = new PdfReader(filePath); AcroFields Fields = Reader.AcroFields; return(Fields.GetSignatureNames().ToArray().Length); }
/** * Switches to the previous revision. * @throws IOException * @throws GeneralSecurityException */ virtual public void SwitchToPreviousRevision() { LOGGER.Info("Switching to previous revision."); latestRevision = false; dss = reader.Catalog.GetAsDict(PdfName.DSS); DateTime cal = pkcs7.TimeStampDate; if (cal == DateTime.MaxValue) { cal = pkcs7.SignDate; } // TODO: get date from signature signDate = cal; List <String> names = fields.GetSignatureNames(); if (names.Count > 1) { signatureName = names[names.Count - 2]; reader = new PdfReader(fields.ExtractRevision(signatureName)); fields = reader.AcroFields; names = fields.GetSignatureNames(); signatureName = names[names.Count - 1]; pkcs7 = CoversWholeDocument(); if (LOGGER.IsLogging(Level.INFO)) { LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName)); } } else { LOGGER.Info("No signatures in revision"); pkcs7 = null; } }
public void AddLtv(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient tsa) { PdfReader r = new PdfReader(src); FileStream fos = new FileStream(dest, FileMode.Create); PdfStamper stp = PdfStamper.CreateSignature(r, fos, '\0', null, true); LtvVerification v = stp.LtvVerification; AcroFields fields = stp.AcroFields; List <String> names = fields.GetSignatureNames(); String sigName = names[names.Count - 1]; PdfPKCS7 pkcs7 = fields.VerifySignature(sigName); if (pkcs7.IsTsp) { v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO); } else { foreach (String name in names) { v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO); } } PdfSignatureAppearance sap = stp.SignatureAppearance; LtvTimestamp.Timestamp(sap, tsa, null); }
private string checkSignature(byte[] pdfContent) { PdfReader reader = new PdfReader(pdfContent); AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); // Signature eklenmiş PDF dosyası buraya yollanmalı. Yoksa Verification Gerçekleşemez. if (names.Count == 0) { return("İlgili PDF'e ait imza(lar) bulunamamıştır."); } string message = string.Empty; for (int i = 1; i < names.Count + 1; i++) { string temp = string.Empty; PdfPKCS7 pkcs7 = fields.VerifySignature(names[i - 1]); var result = pkcs7.Verify(); if (result) { temp = string.Format("{0}.imza geçerli.", i); } else { temp = string.Format("{0}.imza geçersiz.", i); } message += temp; } reader.Close(); return(message); }
void Button4Click(object sender, EventArgs e) { if (!tsaCbx.Checked || TSAUrlTextBox.Text == "") { MessageBox.Show("Marca temporale non selezionata, oppure server non definito"); return; } string TSA_URL = TSAUrlTextBox.Text; string TSA_ACCNT = tsaLogin.Text; string TSA_PASSW = tsaPwd.Text; if (fbd.ShowDialog() == DialogResult.OK) { string foldername = fbd.SelectedPath; string[] files = Directory.GetFiles(foldername, "*.pdf"); pb.Minimum = 0; pb.Maximum = files.Length; pb.Visible = true; lb2.Items.Clear(); foreach (string s in files) { //just filename try { string ext = s.Substring(1 + s.LastIndexOf(@".")).ToLowerInvariant(); if (ext == "pdf" || ext == "PDF") { //ricreo il percorso con il nome del nuovo file string file = s.Substring(1 + s.LastIndexOf(@"\")); string NuovoFile = s.Substring(0, s.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_validato_" + DateTime.Now.ToFileTime() + ".pdf"; PdfReader r = new PdfReader(s); FileStream fout = new FileStream(NuovoFile, FileMode.Create); PdfStamper stp = PdfStamper.CreateSignature(r, fout, '\0', null, true); LtvVerification v = stp.LtvVerification; AcroFields af = stp.AcroFields; foreach (string sigName in af.GetSignatureNames()) { v.AddVerification(sigName, new OcspClientBouncyCastle(), new CrlClientImp(), LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO); } PdfSignatureAppearance sap = stp.SignatureAppearance; TSAClientBouncyCastle tsa = new TSAClientBouncyCastle(TSA_URL, TSA_ACCNT, TSA_PASSW, 6500, "sha256"); LtvTimestamp.Timestamp(sap, tsa, null); lb2.Items.Add(NuovoFile); lb2.Refresh(); pb.Increment(1); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); pb.Visible = false; return; } } MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata"); pb.Visible = false; } }
/** * Creates a VerificationData object for a PdfReader * @param reader a reader for the document we want to verify. * @throws GeneralSecurityException */ public LtvVerifier(PdfReader reader) : base(null) { this.reader = reader; fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); signatureName = names[names.Count - 1]; signDate = DateTime.Now; pkcs7 = CoversWholeDocument(); LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName)); }
/// <summary> /// Nos dice si el pdf está firmado /// </summary> private static bool HasSignatures(String path) { using (PdfReader reader = new PdfReader(path)) { AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); if (names != null && names.Count > 0) { return(true); } return(false); } }
public List <SignatureInfo> InspectSignatures(string path) { PdfReader reader = new PdfReader(path); AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); SignaturePermissions perms = null; var signatureInfoList = new List <SignatureInfo>(); foreach (String name in names) { perms = GetSignatureInfo(fields, name, perms, signatureInfoList); } return(signatureInfoList); }
public void VerifySignatures(String path) { Console.WriteLine(path); PdfReader reader = new PdfReader(path); AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); foreach (string name in names) { Console.WriteLine("===== " + name + " ====="); VerifySignature(fields, name); } Console.WriteLine(); }
public void InspectSignatures(String path) { Console.WriteLine(path); PdfReader reader = new PdfReader(path); AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); SignaturePermissions perms = null; foreach (String name in names) { Console.WriteLine("===== " + name + " ====="); perms = InspectSignature(fields, name, perms); } Console.WriteLine(); }
public IEnumerable <Nenshkrim> MerrNenshkrimet(Stream fajlli) { fajlli.Position = 0; PdfReader pdfReader = new PdfReader(fajlli); AcroFields af = pdfReader.AcroFields; List <string> names = af.GetSignatureNames(); foreach (string name in names) { yield return(MerrNenshkrimInfo(af, name)); } pdfReader.Close(); }
private string GetSignatureName() { AcroFields fields = this.pdfReader.AcroFields; List <string> signatureNames = fields.GetSignatureNames(); if (!signatureNames.Any()) { throw new Exception("No signatures found."); } if (signatureNames.Count > 1) { throw new NotSupportedException("Multiple signatures not supported."); } return(signatureNames.First()); }
public bool IsSignedPDF(byte[] input) { try { PdfReader reader = new PdfReader(input); AcroFields af = reader.AcroFields; var names = af.GetSignatureNames(); return(names.Count > 0); } catch (Exception) { return(false); } }
/** * Call this method to have LTV information added to the {@link PdfStamper} * given in the constructor. */ public void enable(IOcspClient ocspClient, ICrlClient crlClient) { AcroFields fields = pdfStamper.AcroFields; bool encrypted = pdfStamper.Reader.IsEncrypted(); List <String> names = fields.GetSignatureNames(); foreach (String name in names) { PdfPKCS7 pdfPKCS7 = fields.VerifySignature(name); PdfDictionary signatureDictionary = fields.GetSignatureDictionary(name); X509Certificate certificate = pdfPKCS7.SigningCertificate; addLtvForChain(certificate, ocspClient, crlClient, getSignatureHashKey(signatureDictionary, encrypted)); } outputDss(); }
public static bool validatePDF(string filename, ref MessageReport msg) { try { X509CertificateParser parser = new X509CertificateParser(); if (certificates.Count() == 0) { certificates.Add(parser.ReadCertificate(new FileStream(ROOT1, FileMode.Open))); certificates.Add(parser.ReadCertificate(new FileStream(ROOT2, FileMode.Open))); certificates.Add(parser.ReadCertificate(new FileStream(ROOT3, FileMode.Open))); } PdfReader pdfReader = new PdfReader(filename); AcroFields acroFields = pdfReader.AcroFields; List <String> signatureNames = acroFields.GetSignatureNames(); msg.signaturesCount = signatureNames.Count(); if (signatureNames.Count == 0) { msg.StatusText = "Δεν βρέθηκαν ψηφιακές υπογραφές στο έγγραφο!"; return(false); } SignaturePermissions perms = null; MessageReport.Signature sigInfo = new MessageReport.Signature(); foreach (String name in signatureNames) { sigInfo = InspectSignature(acroFields, name, perms); UpdateSignatureResults(ref sigInfo); //produce human friendly result text msg.Signatures.Add(sigInfo); } msg.StatusText = String.Format("Ο έλεγχος ολοκληρώθηκε επιτυχώς. Βρέθηκαν {0} ψηφιακές υπογραφές στο έγγραφο!", msg.signaturesCount); return(true); } catch { return(false); } } //end validatePDF
public void VerifyDigitalSig(byte[] pdf, string signatureName) { PdfReader pdfReader = new PdfReader(pdf); AcroFields acroField = pdfReader.AcroFields; if (signatureName == null || "".CompareTo(signatureName) != 0) { signatureName = acroField.GetSignatureNames().Last(); } PdfPKCS7 pdfP7 = acroField.VerifySignature(signatureName); if (pdfP7 == null) { throw new NullReferenceException("Invalid signatureName:" + signatureName); } if (!pdfP7.Verify()) { throw new PdfException("Unable to verify specified signature field, specify signature invalid"); } //byte[] pkcs7Signatue = pdfP7.GetEncodedPKCS7(); //CmsSignedData signedData = new CmsSignedData(pkcs7Signatue); //Org.BouncyCastle.X509.X509Certificate[] signedCerts = pdfP7.Certificates; //// verifify certificate chain , crlList //// Get signer certificate from CMSSignedData //IX509Store x509Certs = signedData.GetCertificates("Collection"); //ICollection cerlist = x509Certs.GetMatches(null); //IEnumerator cEnum = cerlist.GetEnumerator(); //ArrayList _chain = new ArrayList(); //while (cEnum.MoveNext()) //{ // Org.BouncyCastle.X509.X509Certificate cer = (Org.BouncyCastle.X509.X509Certificate)cEnum.Current; // X509Certificate2 cer2 = new X509Certificate2(cer.GetEncoded()); // _chain.Add(cer2); //} //X509Certificate2[] certChain = (X509Certificate2[])_chain.ToArray(typeof(X509Certificate2)); //validateSignature(signedData, certChain[0]); }
public void loadSignInfo(string pdf_filename) { PdfReader reader = new PdfReader(pdf_filename); AcroFields fields = reader.AcroFields; int sigIndex = 1; SignatureImageExtractor extractor = new SignatureImageExtractor(reader); foreach (string sigFieldName in fields.GetSignatureNames()) { PdfImageObject image = extractor.extractImage(sigFieldName); MemoryStream ms = new MemoryStream(image.GetImageAsBytes()); SigObj sig = new SigObj(); ReadEncodedBitmapResult result = sig.ReadEncodedBitmap(ms.ToArray()); if (result == ReadEncodedBitmapResult.ReadEncodedBitmapOK) { //MessageBox.Show(sig.Who + " " + sig.Why + " " + sig.When); treeView1.BeginUpdate(); treeView1.Nodes.Add("Signature " + sigIndex); treeView1.Nodes[sigIndex - 1].Nodes.Add("Name: " + sig.Who); treeView1.Nodes[sigIndex - 1].Nodes.Add("Reason: " + sig.Why); treeView1.Nodes[sigIndex - 1].Nodes.Add("Timestamp: " + sig.When); treeView1.Nodes[sigIndex - 1].Nodes.Add("Digitizer: " + sig.get_AdditionalData(CaptData.CaptDigitizer)); treeView1.Nodes[sigIndex - 1].Nodes.Add("Digitizer Driver: " + sig.get_AdditionalData(CaptData.CaptDigitizerDriver)); treeView1.Nodes[sigIndex - 1].Nodes.Add("Machine OS: " + sig.get_AdditionalData(CaptData.CaptMachineOS)); treeView1.Nodes[sigIndex - 1].Nodes.Add("Network Card: " + sig.get_AdditionalData(CaptData.CaptNetworkCard)); treeView1.Nodes[sigIndex - 1].Nodes.Add("Signature Covers whole document: " + fields.SignatureCoversWholeDocument(sigFieldName).ToString()); treeView1.Nodes[sigIndex - 1].Nodes.Add("Document Revision: " + fields.GetRevision(sigFieldName).ToString() + " of " + fields.TotalRevisions.ToString()); PdfPKCS7 pkcs7 = fields.VerifySignature(sigFieldName); treeView1.Nodes[sigIndex - 1].Nodes.Add("Integrity Check OK? " + pkcs7.Verify().ToString()); treeView1.EndUpdate(); sigIndex = sigIndex + 1; } ms.Close(); } treeView1.ExpandAll(); }
/// <summary> /// Verifies the signature of a prevously signed PDF document using the specified public key /// </summary> /// <param name="pdfFile">a Previously signed pdf document</param> /// <param name="publicKeyStream">Public key to be used to verify the signature in .cer format</param> /// <exception cref="System.InvalidOperationException">Throw System.InvalidOperationException if the document is not signed or the signature could not be verified</exception> public static void VerifyPdfSignature(string pdfFile, Stream publicKeyStream) { var parser = new X509CertificateParser(); var certificate = parser.ReadCertificate(publicKeyStream); publicKeyStream.Dispose(); PdfReader reader = new PdfReader(pdfFile); AcroFields af = reader.AcroFields; var names = af.GetSignatureNames(); if (names.Count == 0) { throw new InvalidOperationException("No Signature present in pdf file."); } foreach (string name in names) { if (!af.SignatureCoversWholeDocument(name)) { throw new InvalidOperationException(string.Format("The signature: {0} does not covers the whole document.", name)); } PdfPKCS7 pk = af.VerifySignature(name); var cal = pk.SignDate; var pkc = pk.Certificates; if (!pk.Verify()) { throw new InvalidOperationException("The signature could not be verified."); } if (!pk.VerifyTimestampImprint()) { throw new InvalidOperationException("The signature timestamp could not be verified."); } var fails = CertificateVerification.VerifyCertificates(pkc, new[] { certificate }, null, cal); if (fails != null && fails.Any()) { throw new InvalidOperationException("The file is not signed using the specified key-pair."); } } }
public bool VerificarAssinatura(byte[] pdf) { PdfReader pdfReader = new PdfReader(pdf); AcroFields acroFields = pdfReader.AcroFields; IList <string> signatureNames = acroFields.GetSignatureNames(); bool flag = false; foreach (string current in signatureNames) { PdfPKCS7 pdfPKCS = acroFields.VerifySignature(current); DateTime signDate = pdfPKCS.SignDate; flag = pdfPKCS.Verify(); if (!flag) { break; } } return(flag); }
public static int Main(string[] args) { // Разбираем аргументы if (args.Length < 1) { Console.WriteLine("Pdf.Verify <document>"); return(1); } string document = args[0]; // Открываем документ PdfReader reader = new PdfReader(document); // Получаем подписи из документа AcroFields af = reader.AcroFields; List <string> names = af.GetSignatureNames(); foreach (string name in names) { string message = "Signature name: " + name; message += "\nSignature covers whole document: " + af.SignatureCoversWholeDocument(name); message += "\nDocument revision: " + af.GetRevision(name) + " of " + af.TotalRevisions; Console.WriteLine(message); // Проверяем подпись // szOID_CP_GOST_R3411_12_256 "1.2.643.7.1.1.2.2" Функция хэширования ГОСТ Р 34.11-2012, длина выхода 256 бит PdfPKCS7 pk = af.VerifySignature(name); DateTime cal = pk.SignDate; Org.BouncyCastle.X509.X509Certificate[] pkc = pk.Certificates; message = "Certificate " + pk.SigningCertificate; message += "\nDocument modified: " + !pk.Verify(); message += "\nDate: " + cal.ToShortDateString(); // Проверим сертификат через CAPI X509Certificate2 cert = new X509Certificate2(pk.SigningCertificate.GetEncoded()); var isCAPIValid = cert.Verify(); message += "\nCAPI Validation: " + isCAPIValid.ToString(); Console.WriteLine(message); } return(0); }
static void Main(string[] args) { string pdfValidateUri = @"<FILE_PATH>"; PdfReader reader = new PdfReader(pdfValidateUri); AcroFields fields = reader.AcroFields; List <String> names = fields.GetSignatureNames(); foreach (string name in names) { Console.WriteLine("===== " + name + " ====="); var pkcs7 = fields.VerifySignature(name); var signCert = pkcs7.Certificates[0]; X509Certificate issuerCert = (pkcs7.Certificates.Length > 1 ? pkcs7.Certificates[1] : null); Console.WriteLine("=== Checking validity of the document today ==="); CheckRevocation(pkcs7, signCert, issuerCert, DateTime.Now); } Console.ReadLine(); }
/// <summary> /// Ritorna true se in un file PDF sono presenti delle firme pades /// </summary> /// <param name="fileDoc"></param> /// <returns></returns> private static bool IsPdfPades(PdfReader r) { try { int numSig = 0; AcroFields af = r.AcroFields; if (af != null) { numSig = af.GetSignatureNames().Count; if (numSig > 0) { return(true); } } return(false); } catch { return(false); } }
public byte[] LTVEnable(byte[] pdf, ITSAClient tsaClient) { PdfReader document = new PdfReader(pdf); MemoryStream stream = new MemoryStream(); string signatureName = ""; PdfStamper pdfStamper = new PdfStamper(document, stream, '0', true); //PdfStamper pdfStamper = PdfStamper.CreateSignature(document, stream, '\0'); AcroFields fields = pdfStamper.AcroFields; List <string> _fieldNames = fields.GetSignatureNames(); foreach (string _fieldName in _fieldNames) { signatureName = _fieldName; } LtvVerification v = pdfStamper.LtvVerification; PdfPKCS7 pkcs7 = fields.VerifySignature(signatureName); CrlClientOnline crl = new CrlClientOnline(pkcs7.SignCertificateChain); if (pkcs7.IsTsp) { v.AddVerification(signatureName, null, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.CRL, LtvVerification.CertificateInclusion.NO); } else { v.AddVerification(signatureName, null, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.CRL, LtvVerification.CertificateInclusion.NO); } pdfStamper.Close(); //PdfSignatureAppearance sap = pdfStamper.SignatureAppearance; //LtvTimestamp.Timestamp(sap, tsaClient, null); return(stream.ToArray()); }
public override bool VerifyFile(string filePath, ref List <KeyValuePair <X509Certificate2, bool> > verifiedCMS) { PdfReader Reader = new PdfReader(filePath); AcroFields Fields = Reader.AcroFields; List <String> Names = Fields.GetSignatureNames(); List <KeyValuePair <X509Certificate2, bool> > UsedCertificates = new List <KeyValuePair <X509Certificate2, bool> >(); bool Validation = false; foreach (String Signature in Names) { PdfPKCS7 CMS = Fields.VerifySignature(Signature); bool currentValidation = CMS.Verify(); UsedCertificates.Add(new KeyValuePair <X509Certificate2, bool>(new X509Certificate2(DotNetUtils.ToX509Certificate(CMS.SigningCertificate)), currentValidation)); //If one signature fails, so does the global validation of the file if (!currentValidation) { Validation = false; } } verifiedCMS = UsedCertificates; return(Validation); }
public static SignatureValidation VerifySignature(X509Certificate certificate, string input) { PdfReader reader = new PdfReader(input); AcroFields fields = reader.AcroFields; ArrayList signatureNames = fields.GetSignatureNames(); if (signatureNames.Count == 0) { return(null); } SignatureValidation result = null; foreach (string signatureName in signatureNames) { PdfPKCS7 pkcs7 = fields.VerifySignature(signatureName); if (certificate.SerialNumber.CompareTo(pkcs7.SigningCertificate.SerialNumber) == 0) { byte[] b1 = certificate.GetSignature(); byte[] b2 = pkcs7.SigningCertificate.GetSignature(); if (b1.SequenceEqual(b2)) { result = new SignatureValidation(); result.SignatureDate = pkcs7.SignDate; result.SignatureName = pkcs7.SignName; result.Reason = pkcs7.Reason; result.Location = pkcs7.Location; result.SignatureCoversWholeDocument = fields.SignatureCoversWholeDocument(signatureName); result.Verified = pkcs7.Verify(); result.CertificateValid = true; return(result); } } } return(null); }
private void SignUsingEstEIDCard2(string filename, string outfile) { statusHandler(Resources.VERIFYING_DOCUMENT, false); AcroFields af = this.reader.AcroFields; ArrayList names = af.GetSignatureNames(); bool nextRevision = ((names != null) && (names.Count > 0)); // already signed ? if (nextRevision) { // pick always first signature string name = (string)names[0]; PdfPKCS7 pkc7 = af.VerifySignature(name); bool verify = pkc7.Verify(); if (!verify) { string who = PdfPKCS7.GetSubjectFields(pkc7.SigningCertificate).GetField("CN"); throw new DocVerifyException(Resources.DOC_VERIFY_FAILED + who); } } statusHandler(Resources.CONNECTING_SMARTCARD, false); // open EstEID EstEIDReader estEidReader = new EstEIDReader(); string pkcs11_lib = conf.PKCS11DriverPath; bool b = estEidReader.Open(pkcs11_lib); if (b == false) { throw new Exception(Resources.PKCS11_OPEN); } statusHandler(Resources.READ_CERTS, false); PKCS11Signer signer = LocateSigner(estEidReader); Org.BouncyCastle.X509.X509Certificate[] chain = X509Utils.LoadCertificate(signer.Cert.RawData); statusHandler(Resources.VERIFYING_OCSP, false); OCSPClientEstEID ocspClient = OCSPClient(chain[0]); if (ocspClient == null) { throw new Exception(this.lastError); } byte[] ocsp = ocspClient.GetEncoded(); if (ocsp == null) { throw new RevocationException(ocspClient.lastError); } X509Certificate2 card = signer.Cert; Oid oid = card.SignatureAlgorithm; if (oid.Value != PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { throw new Exception(Resources.INVALID_CERT); } PdfReader reader = new PdfReader(filename); Document document = new Document(reader.GetPageSizeWithRotation(1)); PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(outfile, FileMode.Create), '\0', null, nextRevision); if (metadata != null) { stp.XmpMetadata = metadata.getStreamedMetaData(); } PdfSignatureAppearance sap = stp.SignatureAppearance; if (appearance.Visible) { if (appearance.SigLocation.UseSector) { appearance.SigLocation.Bounds = document.PageSize; } sap.SetVisibleSignature(appearance.SigLocation, (int)appearance.Page, null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Reason = (appearance.Reason.Length > 0) ? appearance.Reason : null; sap.Location = (appearance.Location.Length > 0) ? appearance.Location : null; sap.Contact = (appearance.Contact.Length > 0) ? appearance.Contact : null; sap.Acro6Layers = true; sap.Render = appearance.SignatureRender; sap.Layer2Text = appearance.SignatureText(sap.SignDate, chain[0]); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_SHA1); 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; sap.SetExternalDigest(new byte[SIGNATURE_LENGTH], new byte[Digest.SHA1_LENGTH], "RSA"); // expect 6K to be enough if TSA response, else 2K ? int csize = (stamp != null) ? 1024 * 6 : 1024 * 2; Hashtable exc = new Hashtable(); exc[PdfName.CONTENTS] = csize * 2 + 2; sap.PreClose(exc); // compute hash based on PDF bytes byte[] digest = ComputeHash(estEidReader, sap); statusHandler(Resources.ADD_SIGNATURE, false); // sign hash byte[] rsadata = EstEIDCardSign(estEidReader, signer, digest); // if null, user requested Cancel if (rsadata == null) { throw new Exception(Resources.CARD_INTERNAL_ERROR); } // create PKCS#7 envelope PdfPKCS7 pk7 = new PdfPKCS7(null, chain, null, "SHA1", true); pk7.SetExternalDigest(rsadata, digest, "RSA"); byte[] pk = pk7.GetEncodedPKCS7(); // user wants to add TSA response ? if (stamp != null && pk != null) { statusHandler(Resources.TSA_REQUEST, false); pk = TimestampAuthorityResponse(estEidReader, pk); } // PKCS#7 bytes too large ? if (pk.Length >= csize) { throw new Exception(Resources.MEMORY_ERROR); } byte[] outc = new byte[csize]; PdfDictionary dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sap.Close(dic2); }
/** * Creates a VerificationData object for a PdfReader * @param reader a reader for the document we want to verify. * @throws GeneralSecurityException */ public LtvVerifier(PdfReader reader) : base(null) { this.reader = reader; fields = reader.AcroFields; List<String> names = fields.GetSignatureNames(); signatureName = names[names.Count - 1]; signDate = DateTime.Now; pkcs7 = CoversWholeDocument(); LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName)); }
/** * Switches to the previous revision. * @throws IOException * @throws GeneralSecurityException */ virtual public void SwitchToPreviousRevision() { LOGGER.Info("Switching to previous revision."); latestRevision = false; dss = reader.Catalog.GetAsDict(PdfName.DSS); DateTime cal = pkcs7.TimeStampDate; if (cal == DateTime.MaxValue) cal = pkcs7.SignDate; // TODO: get date from signature signDate = cal; List<String> names = fields.GetSignatureNames(); if (names.Count > 1) { signatureName = names[names.Count - 2]; reader = new PdfReader(fields.ExtractRevision(signatureName)); fields = reader.AcroFields; names = fields.GetSignatureNames(); signatureName = names[names.Count - 1]; pkcs7 = CoversWholeDocument(); LOGGER.Info(String.Format("Checking {0}signature {1}", pkcs7.IsTsp ? "document-level timestamp " : "", signatureName)); } else { LOGGER.Info("No signatures in revision"); pkcs7 = null; } }
static void Main(string[] args) { //string resultFile = Directory.GetCurrentDirectory().ToString() + @"\Result_" + currentDate + ".xlsx"; try { Menu(args); if (!Directory.Exists(dstFolder)) { Directory.CreateDirectory(dstFolder); } resultFile = dstFolder + @"\Result_" + currentDate + ".xlsx"; // Creating excel file excel = new Application { Visible = false, DisplayAlerts = false }; wb = excel.Workbooks.Add(Type.Missing); ws = wb.ActiveSheet; ws.Name = "Result"; // Set first row headers to filter later ws.Cells[row, 1] = "Directory Name"; ws.Cells[row, 2] = "File Name"; ws.Cells[row, 3] = "Signing Status"; row++; // Get all target filenames from directory including sub-directories filenames = Directory.EnumerateFiles(srcFolder, "*.pdf", SearchOption.AllDirectories); foreach (string temp in filenames) { filename = temp; try { using (var doc = new PdfReader(filename)) { AcroFields acroFields = doc.AcroFields; // Checking if signature fields exist if (acroFields.GetSignatureNames().Count != 0) { ws.Cells[row, 1] = Path.GetDirectoryName(filename); ws.Cells[row, 2] = Path.GetFileName(filename); ws.Cells[row, 3] = "signed"; row++; } else { ws.Cells[row, 1] = Path.GetDirectoryName(filename); ws.Cells[row, 2] = Path.GetFileName(filename); ws.Cells[row, 3] = "unsigned"; row++; } } } catch (InvalidPdfException e) { ws.Cells[row, 1] = Path.GetDirectoryName(filename); ws.Cells[row, 2] = Path.GetFileName(filename); ws.Cells[row, 3] = "Corrupted or non conformant to PDF standard"; row++; } } } // end try catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); } // Adding Autofilter ws.UsedRange.AutoFilter(1, Type.Missing, XlAutoFilterOperator.xlAnd, Type.Missing, true); ws.Columns.AutoFit(); wb.SaveAs(resultFile); excel.Visible = true; }
/// <summary> /// Remove a assinatura de um documento PDF /// </summary> internal static void remove(string filePath, string serialNumber = null) { try { // create a tmp file to remove string newFilePath = filePath.Substring(0, filePath.Length - 4) + "_tmp.pdf"; System.IO.File.Copy(filePath, newFilePath); // open the file PdfReader reader = new PdfReader(newFilePath); // get the fields inside the file AcroFields af = reader.AcroFields; // get the list of signatures List <string> names = af.GetSignatureNames(); if (names.Count == 0) { reader.Close(); throw new NoSignatureFoundException(); } // create the stream to file MemoryStream mStream = new MemoryStream(); // open the file to edit PdfStamper stamper = new PdfStamper(reader, mStream); AcroFields af2 = stamper.AcroFields; // close the reader file reader.Close(); if (serialNumber == null) { // remove all signatures for (int i = 0; i < names.Count; i++) { //af2.ClearSignatureField(names[i].ToString()); af2.RemoveField(names[i].ToString()); } } else { // find and remove the selected signature for (int i = 0; i < names.Count; i++) { PdfPKCS7 pk = af.VerifySignature(names[i]); if (pk.SigningCertificate.SerialNumber.ToString(16).ToUpper() == serialNumber) { //af2.ClearSignatureField(names[i].ToString()); af2.RemoveField(names[i].ToString()); } } } // clear the stream of obejct reader.RemoveUnusedObjects(); // close the stamper file stamper.Writer.CloseStream = false; stamper.Close(); // save file File.WriteAllBytes(newFilePath, mStream.ToArray()); // delete the tmp file e move the new to the right name System.IO.File.Delete(filePath); System.IO.File.Move(newFilePath, filePath); } catch (Exception ex) { throw ex; } }
static void Main(string[] args) { string CurrentDirectory = Directory.GetCurrentDirectory(); CurrentDirectory = CurrentDirectory.Substring(0, CurrentDirectory.LastIndexOf("bin", CurrentDirectory.Length - 1)); string PdfFileName = CurrentDirectory + "TestPdf.pdf"; if (File.Exists(PdfFileName)) { File.Delete(PdfFileName); } Document pdfDocument = new Document(); PdfWriter writer = PdfWriter.GetInstance(pdfDocument, new FileStream(PdfFileName, FileMode.Create)); pdfDocument.Open(); pdfDocument.AddTitle("Title"); pdfDocument.AddAuthor("Author"); pdfDocument.AddSubject("Subject"); pdfDocument.AddCreator("Creator"); string tmpString = "tmpString"; pdfDocument.Add(new Paragraph(tmpString)); pdfDocument.Close(); PdfReader reader = new PdfReader(PdfFileName); string PdfFileNameOut = CurrentDirectory + "TestPdfOut.pdf"; if (File.Exists(PdfFileNameOut)) { File.Delete(PdfFileNameOut); } PdfStamper stamper = new PdfStamper(reader, new FileStream(PdfFileNameOut, FileMode.Create)); AcroFields fields = stamper.AcroFields; bool result; result = fields.SetField("name", "name", "name"); result = fields.SetField("address", "address", "address"); result = fields.SetField("postal_code", "postal_code", "postal_code"); result = fields.SetField("email", "email", "email"); stamper.FormFlattening = true; stamper.Close(); reader.Close(); reader = new PdfReader(PdfFileNameOut); fields = reader.AcroFields; List <string> allNames = fields.GetSignatureNames(), blankNames = fields.GetBlankSignatureNames(); reader.Close(); }
/// <summary> /// Verifiy of CRL /// </summary> /// <param name="fileContents">byte Array file contents</param> /// <param name="endPoint">not used </param> /// <param name="args">1) Datetime? data verifica / string cachePath / string (bool) nocache</param> /// <returns></returns> public EsitoVerifica VerificaByteEV(byte[] fileContents, string endPoint, Object[] args) { //string ID = String.Format("{0}-{1}", Environment.GetEnvironmentVariable("APP_POOL_ID").Replace(" ", ""), AppDomain.CurrentDomain.BaseDirectory); bool forceDownload = false; //end point lo usiamo per forzare il download string p7mSignAlgorithm = null; //string p7mSignHash = null; DocsPaVO.documento.Internal.SignerInfo[] certSignersInfo; EsitoVerifica ev = new EsitoVerifica(); DateTime?dataverificaDT = null; string cachePath = string.Empty; if (args == null) { logger.Debug("Args (Date) is null, settign current"); dataverificaDT = DateTime.Now; } if (args.Length > 0) { dataverificaDT = args[0] as DateTime?; if (dataverificaDT == null) { logger.Debug("Date is null, settign current"); dataverificaDT = DateTime.Now; } cachePath = args[1] as string; string fdl = args[2] as string; if (!String.IsNullOrEmpty(fdl)) { Boolean.TryParse(endPoint, out forceDownload); } } int posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("Mime-Version:")); if (posi == 0) //E' un mime m7m { using (MemoryStream ms = new MemoryStream(fileContents)) { anmar.SharpMimeTools.SharpMessage sm = new anmar.SharpMimeTools.SharpMessage(ms); if (sm.Attachments.Count > 0) { foreach (anmar.SharpMimeTools.SharpAttachment att in sm.Attachments) { if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("p7m")) { att.Stream.Position = 0; BinaryReader sr = new BinaryReader(att.Stream); fileContents = sr.ReadBytes((int)att.Size); } } } } } // Ce provo.... posi = -1; posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("%PDF")); if (posi == 0) //E' un pdf { PdfReader pdfReader = isPdf(fileContents); try { AcroFields af = pdfReader.AcroFields; List <string> signNames = af.GetSignatureNames(); if (signNames.Count == 0) //Firma non è presente { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Il file PDF da verificare non contiene nessuna firma"; ev.errorCode = "1458"; return(ev); } List <DocsPaVO.documento.Internal.SignerInfo> siList = new List <DocsPaVO.documento.Internal.SignerInfo>(); foreach (string name in signNames) { PdfPKCS7 pk = af.VerifySignature(name); p7mSignAlgorithm = pk.GetHashAlgorithm(); Org.BouncyCastle.X509.X509Certificate[] certs = pk.Certificates; foreach (X509Certificate cert in certs) { DocsPaVO.documento.Internal.SignerInfo si = GetCertSignersInfo(cert); VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert, p7mSignAlgorithm); si = ControlloCRL(forceDownload, ev, cachePath, cert, si); siList.Add(si); } bool result = pk.Verify(); if (!result) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "La verifica della firma è fallita (File is Tampered)"; ev.errorCode = "1450"; } } /* * if ( * (pdfReader.PdfVersion.ToString() != "4")|| * (pdfReader.PdfVersion.ToString() != "7")) * { * ev.status = EsitoVerificaStatus.ErroreGenerico; * ev.message = "Il file da verificare non è conforme allo standard PDF 1.4 o pdf 1.7"; * ev.errorCode = "1457"; * } */ List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>(); DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document { SignersInfo = siList.ToArray(), DocumentFileName = null, Level = 0 }; p7docsLst.Add(p7doc); ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray()); ev.content = fileContents; } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying pdf message :" + e.Message; ev.errorCode = "1402"; return(ev); } } else //PKCS7 { try { int doclevel = 0; List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>(); do { //questa Estrazione serve solo per capire se uscire dal ciclo ricorsivo e ritornare il content try { ev.content = extractSignedContent(fileContents); } catch { break; } //Ciclo per file firmato Asn1Sequence sequenza = Asn1Sequence.GetInstance(fileContents); DerObjectIdentifier tsdOIDFile = sequenza[0] as DerObjectIdentifier; if (tsdOIDFile != null) { if (tsdOIDFile.Id == CmsObjectIdentifiers.timestampedData.Id) //TSD { logger.Debug("Found TSD file"); DerTaggedObject taggedObject = sequenza[1] as DerTaggedObject; if (taggedObject != null) { Asn1Sequence asn1seq = Asn1Sequence.GetInstance(taggedObject, true); TimeStampedData tsd = TimeStampedData.GetInstance(asn1seq); fileContents = tsd.Content.GetOctets(); } } if (tsdOIDFile.Id == CmsObjectIdentifiers.SignedData.Id) //p7m { logger.Debug("Found P7M file"); } } CmsSignedData cms = new CmsSignedData(fileContents); //controllaCrlFileP7m(cms); IX509Store store = cms.GetCertificates("Collection"); SignerInformationStore signers = cms.GetSignerInfos(); SignedData da = SignedData.GetInstance(cms.ContentInfo.Content.ToAsn1Object()); Asn1Sequence DigAlgAsn1 = null; if (da.DigestAlgorithms.Count > 0) { DigAlgAsn1 = da.DigestAlgorithms[0].ToAsn1Object() as Asn1Sequence; } if (DigAlgAsn1 != null) { p7mSignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID); } certSignersInfo = new DocsPaVO.documento.Internal.SignerInfo[signers.GetSigners().Count]; int i = 0; foreach (SignerInformation signer in signers.GetSigners()) { bool fileOK = false; Org.BouncyCastle.X509.X509Certificate cert1 = GetCertificate(signer, store); certSignersInfo[i] = GetCertSignersInfo(cert1); VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert1, p7mSignAlgorithm); fileOK = VerificaNonRepudiation(ev, fileOK, cert1); if (!fileOK) { certSignersInfo[i].CertificateInfo.messages = ev.errorCode + " " + ev.message; } try { fileOK = VerificaCertificato(ev, signer, fileOK, cert1); } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying 2, message :" + e.Message; ev.errorCode = "1450"; } if (fileOK) { certSignersInfo[i] = ControlloCRL(forceDownload, ev, cachePath, cert1, certSignersInfo[i]); } //p7mSignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID), (byte[])cms.SignedContent.GetContent())).Replace("-", ""); } /* * if (cms.SignedContent != null) * { * //CmsProcessable signedContent = cms.SignedContent; * //ev.content = (byte[])signedContent.GetContent(); * * ev.content = extractMatrioskaFile(fileContents); * * * * } */ DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document { SignersInfo = certSignersInfo, DocumentFileName = null, Level = doclevel++ }; p7docsLst.Add(p7doc); try { fileContents = extractSignedContent(fileContents); } catch { break; } } while (true); ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());; } catch (Exception e) { ev.status = EsitoVerificaStatus.ErroreGenerico; ev.message = "Error verifying 1, message :" + e.Message; ev.errorCode = "1402"; return(ev); } } return(ev); }