CryptoPro

Verify PDF using .NET and iText

Apr 20th, 2012
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.44 KB | None | 0 0
  1. using System;
  2. using System.Security.Cryptography.X509Certificates;
  3. using System.IO.Packaging;
  4.  
  5. #if PDF_SIGNATURE_ENABLED
  6. namespace Simple35.Pdf
  7. {
  8.     using iTextSharp.text.pdf;
  9.     using System.IO;
  10.     using Org.BouncyCastle.X509;
  11.     using System.Security.Cryptography.Pkcs;
  12.     using System.Collections.Generic;    
  13.     /// <summary>
  14.     /// Для сборки примера необходимо установить последнюю версию iTextSharp и определить переменную PDF_SIGNATURE_ENABLED
  15.     /// </summary>
  16.     public class Verify
  17.     {
  18.  
  19.         [STAThread]
  20.         public static int Main(string[] args)
  21.         {
  22.             // Разбираем аргументы
  23.             if (args.Length < 1)
  24.             {
  25.                 Console.WriteLine("Pdf.Verify <document>");
  26.                 return 1;
  27.             }
  28.             string document = args[0];
  29.  
  30.             // Открываем документ
  31.             PdfReader reader = new PdfReader(document);
  32.  
  33.             // Получаем подписи из документа
  34.             AcroFields af = reader.AcroFields;
  35.             List<string> names = af.GetSignatureNames();
  36.             foreach (string name in names)
  37.             {
  38.                 string message = "Signature name: " + name;
  39.                 message += "\nSignature covers whole document: " + af.SignatureCoversWholeDocument(name);
  40.                 message += "\nDocument revision: " + af.GetRevision(name) + " of " + af.TotalRevisions;
  41.                 Console.WriteLine(message);
  42.  
  43.                 // Проверяем подпись
  44.                 PdfPKCS7 pk = af.VerifySignature(name);
  45.                 DateTime cal = pk.SignDate;
  46.                 Org.BouncyCastle.X509.X509Certificate[] pkc = pk.Certificates;
  47.                 message = "Subject: " + PdfPKCS7.GetSubjectFields(pk.SigningCertificate).GetField("CN");
  48.                 message += "\nDocument modified: " + !pk.Verify();
  49.                 message += "\nDate: " + cal.ToShortDateString();
  50.  
  51.                 // Проверим сертификат через CAPI    
  52.                 X509Certificate2 cert = new X509Certificate2(pk.SigningCertificate.GetEncoded());
  53.                 var isCAPIValid = cert.Verify();
  54.                 message += "\nCAPI Validation: " + isCAPIValid.ToString();
  55.                 Console.WriteLine(message);
  56.             }          
  57.  
  58.             return 0;
  59.         }
  60.     }
  61. }
  62. #endif
Advertisement
Add Comment
Please, Sign In to add comment