예제 #1
0
 public static int CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
 {
     List<BasicOcspResp> ocsps = new List<BasicOcspResp>();
     if (pkcs7.Ocsp != null)
         ocsps.Add(pkcs7.Ocsp);
     OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
     List<VerificationOK> verification =
         ocspVerifier.Verify(signCert, issuerCert, date);
     if (verification.Count == 0)
     {
         List<X509Crl> crls = new List<X509Crl>();
         if (pkcs7.CRLs != null)
             foreach (X509Crl crl in pkcs7.CRLs)
                 crls.Add(crl);
         CrlVerifier crlVerifier = new CrlVerifier(null, crls);
         verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
     }
     if (verification.Count == 0)
     {
         Console.WriteLine("No se pudo verificar estado de revocación del certificado por CRL ni OCSP");
         return CER_STATUS_NOT_VERIFIED;
     }
     else
     {
         foreach (VerificationOK v in verification)
             Console.WriteLine(v);
         return 0;
     }
 }
예제 #2
0
        public static void addLTV(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient itsaClient)
        {
            PdfReader       reader        = new PdfReader(src);
            PdfWriter       writer        = new PdfWriter(dest);
            PdfDocument     pdfDoc        = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
            LtvVerification v             = new LtvVerification(pdfDoc);
            SignatureUtil   signatureUtil = new SignatureUtil(pdfDoc);
            IList <string>  names         = signatureUtil.GetSignatureNames();
            String          sigName       = names[names.Count - 1];
            PdfPKCS7        pkcs7         = signatureUtil.ReadSignatureData(sigName);

            if (pkcs7.IsTsp())
            {
                v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                  LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
            }
            else
            {
                foreach (var name in names)
                {
                    v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN,
                                      LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
                }
            }
            v.Merge();
            pdfDoc.Close();
        }
예제 #3
0
        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);
        }
        /// <summary>
        /// Method that will be called during the signing process
        /// </summary>
        /// <param name="data">Stream with the doc data that should be used in the hasing process</param>
        /// <returns></returns>
        public override byte[] Sign(Stream data)
        {
            // crea pdf pkcs7 for signing the document
            var sgn = new PdfPKCS7(null,
                                   _certificates.ToArray(),
                                   DigestAlgorithms.SHA256,
                                   false);

            // get hash for document bytes
            NakedHash = DigestAlgorithms.Digest(data, DigestAlgorithms.SHA256);

            // get attributes
            var docBytes = sgn.GetAuthenticatedAttributeBytes(NakedHash,
                                                              PdfSigner.CryptoStandard.CMS,
                                                              _ocspBytes?.ToList(),
                                                              _crlBytesCollection?.ToList());

            // hash it again
            using var hashMemoryStream = new MemoryStream(docBytes, false);
            var docBytesHash = DigestAlgorithms.Digest(hashMemoryStream, DigestAlgorithms.SHA256);


            //prepend sha256 prefix
            var totalHash = new byte[_sha256SigPrefix.Length + docBytesHash.Length];

            _sha256SigPrefix.CopyTo(totalHash, 0);
            docBytesHash.CopyTo(totalHash, _sha256SigPrefix.Length);
            HashToBeSignedByAma = totalHash;
            return(Array.Empty <byte>());
        }
예제 #5
0
        /* Updates the /ByteRange with the provided value */
        private void UpdateByteRange(PdfPKCS7 pkcs7, PdfSignature signature)
        {
            PdfArray b = signature.GetByteRange();
            RandomAccessFileOrArray rf = document.GetReader().GetSafeFile();
            Stream rg = null;

            try {
                rg = new RASInputStream(new RandomAccessSourceFactory().CreateRanged(rf.CreateSourceView(), b.ToLongArray(
                                                                                         )));
                byte[] buf = new byte[8192];
                int    rd;
                while ((rd = rg.JRead(buf, 0, buf.Length)) > 0)
                {
                    pkcs7.Update(buf, 0, rd);
                }
            }
            catch (Exception e) {
                throw new PdfException(e);
            }
            finally {
                try {
                    if (rg != null)
                    {
                        rg.Dispose();
                    }
                }
                catch (System.IO.IOException e) {
                    // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway
                    throw new PdfException(e);
                }
            }
        }
예제 #6
0
        private SignaturePermissions GetSignatureInfo(AcroFields fields, string name, SignaturePermissions perms, List <SignatureInfo> signatureInfoList)
        {
            var si = new SignatureInfo();

            PdfPKCS7 pkcs7 = fields.VerifySignature(name);

            X509Certificate cert    = pkcs7.SigningCertificate;
            PdfDictionary   sigDict = fields.GetSignatureDictionary(name);
            PdfString       contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }


            si.Signer         = CertificateInfo.GetSubjectFields(cert).GetField("CN");
            si.SignedOn       = pkcs7.SignDate;
            si.Location       = pkcs7.Location;
            si.Issuer         = cert.IssuerDN.ToString();
            si.Subject        = cert.SubjectDN.ToString();
            si.CertValidFrom  = cert.NotBefore;
            si.CertValidTo    = cert.NotAfter;
            si.Reason         = pkcs7.Reason;
            si.IntegrityCheck = pkcs7.Verify();
            signatureInfoList.Add(si);

            perms = new SignaturePermissions(sigDict, perms);

            return(perms);
        }
예제 #7
0
        private String calculateSigningContent(X509Certificate2 cert)
        {
            byte[] sh = null;
            try
            {
                Org.BouncyCastle.X509.X509Certificate[] chain = GetCertChain(cert);
                sgn       = new PdfPKCS7(null, chain, "SHA-256", true);
                hashValue = HashFile(sap.GetRangeStream());
                List <ICrlClient> crlList = new List <ICrlClient>();
                crlList.Add(new CrlClientOnline(chain));

                ICollection <byte[]> crlBytes = null;
                int i = 0;
                while (crlBytes == null && i < chain.Length)
                {
                    crlBytes = MakeSignature.ProcessCrl(chain[i++], null);
                }

                sh = sgn.getAuthenticatedAttributeBytes(hashValue, null, crlBytes /*crlbyte*/, CryptoStandard.CADES);
            }
            catch (Exception ex)
            {
                if (document != null)
                {
                    document.Close();
                }
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                throw new Exception("getHash : " + ex.Message, ex);
            }
            return(System.Convert.ToBase64String(sh));
        }
예제 #8
0
        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);
        }
        public virtual void TestISAValidPdf()
        {
            String        filePath      = sourceFolder + "isaValidPdf.pdf";
            String        signatureName = "Signature1";
            PdfDocument   document      = new PdfDocument(new PdfReader(filePath));
            SignatureUtil sigUtil       = new SignatureUtil(document);
            PdfPKCS7      pdfPKCS7      = sigUtil.ReadSignatureData(signatureName);

            NUnit.Framework.Assert.IsTrue(pdfPKCS7.VerifySignatureIntegrityAndAuthenticity());
            NUnit.Framework.Assert.IsFalse(sigUtil.SignatureCoversWholeDocument(signatureName));
            String textFromPage = PdfTextExtractor.GetTextFromPage(document.GetPage(1));

            // We are working with the latest revision of the document, that's why we should get amended page text.
            // However Signature shall be marked as not covering the complete document, indicating its invalidity
            // for the current revision.
            NUnit.Framework.Assert.AreEqual("This is manipulated malicious text, ha-ha!", textFromPage);
            NUnit.Framework.Assert.AreEqual(2, sigUtil.GetTotalRevisions());
            NUnit.Framework.Assert.AreEqual(1, sigUtil.GetRevision(signatureName));
            Stream        sigInputStream      = sigUtil.ExtractRevision(signatureName);
            PdfDocument   sigRevDocument      = new PdfDocument(new PdfReader(sigInputStream));
            SignatureUtil sigRevUtil          = new SignatureUtil(sigRevDocument);
            PdfPKCS7      sigRevSignatureData = sigRevUtil.ReadSignatureData(signatureName);

            NUnit.Framework.Assert.IsTrue(sigRevSignatureData.VerifySignatureIntegrityAndAuthenticity());
            NUnit.Framework.Assert.IsTrue(sigRevUtil.SignatureCoversWholeDocument(signatureName));
            sigRevDocument.Close();
            document.Close();
        }
예제 #10
0
        /// <summary>Switches to the previous revision.</summary>
        public virtual void SwitchToPreviousRevision()
        {
            LOGGER.Info("Switching to previous revision.");
            latestRevision = false;
            dss            = document.GetCatalog().GetPdfObject().GetAsDictionary(PdfName.DSS);
            DateTime cal = pkcs7.GetTimeStampDate();

            if (cal == TimestampConstants.UNDEFINED_TIMESTAMP_DATE)
            {
                cal = pkcs7.GetSignDate();
            }
            // TODO: get date from signature
            signDate = cal.ToUniversalTime();
            IList <String> names = sgnUtil.GetSignatureNames();

            if (names.Count > 1)
            {
                signatureName = names[names.Count - 2];
                document      = new PdfDocument(new PdfReader(sgnUtil.ExtractRevision(signatureName)), new DocumentProperties()
                                                .SetEventCountingMetaInfo(metaInfo));
                this.acroForm = PdfAcroForm.GetAcroForm(document, true);
                this.sgnUtil  = new SignatureUtil(document);
                names         = sgnUtil.GetSignatureNames();
                signatureName = names[names.Count - 1];
                pkcs7         = CoversWholeDocument();
                LOGGER.Info(MessageFormatUtil.Format("Checking {0}signature {1}", pkcs7.IsTsp() ? "document-level timestamp "
                     : "", signatureName));
            }
            else
            {
                LOGGER.Info("No signatures in revision");
                pkcs7 = null;
            }
        }
예제 #11
0
        public SignaturePermissions InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    Console.WriteLine("Invisible signature");
                }
                else
                {
                    Console.WriteLine("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}",
                                      fp.page, pos.Left, pos.Bottom, pos.Right, pos.Top);
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name);

            Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm());
            Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm());
            Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype());
            X509Certificate cert = pkcs7.SigningCertificate;

            Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN"));
            if (pkcs7.SignName != null)
            {
                Console.WriteLine("Alternative name of the signer: " + pkcs7.SignName);
            }

            Console.WriteLine("Signed on: " + pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                Console.WriteLine("TimeStamp: " + pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
                TimeStampToken ts = pkcs7.TimeStampToken;
                Console.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa);
                Console.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint());
            }
            Console.WriteLine("Location: " + pkcs7.Location);
            Console.WriteLine("Reason: " + pkcs7.Reason);
            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);
            Console.WriteLine("Signature type: " + (perms.Certification ? "certification" : "approval"));
            Console.WriteLine("Filling out fields allowed: " + perms.FillInAllowed);
            Console.WriteLine("Adding annotations allowed: " + perms.AnnotationsAllowed);
            foreach (SignaturePermissions.FieldLock Lock in perms.FieldLocks)
            {
                Console.WriteLine("Lock: " + Lock);
            }
            return(perms);
        }
예제 #12
0
        private static void SetSigText(PdfSignatureAppearance sigAppearance, IList <X509Certificate> chain)
        {
            sigAppearance.SignDate = DateTime.Now;
            var signedBy = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN");
            var signedOn = sigAppearance.SignDate;

            sigAppearance.Layer2Text = String.Format(SigTextFormat, signedBy, signedOn);
        }
예제 #13
0
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        internal static void BasicCheckSignedDoc(String filePath, String signatureName)
        {
            PdfDocument   outDocument = new PdfDocument(new PdfReader(filePath));
            SignatureUtil sigUtil     = new SignatureUtil(outDocument);
            PdfPKCS7      pdfPKCS7    = sigUtil.VerifySignature(signatureName);

            NUnit.Framework.Assert.IsTrue(pdfPKCS7.Verify());
            outDocument.Close();
        }
예제 #14
0
        virtual public PdfPKCS7 VerifySignature(AcroFields fields, String name)
        {
            Console.WriteLine("Signature covers whole document: " + fields.SignatureCoversWholeDocument(name));
            Console.WriteLine("Document revision: " + fields.GetRevision(name) + " of " + fields.TotalRevisions);
            PdfPKCS7 pkcs7 = fields.VerifySignature(name);

            Console.WriteLine("Integrity check OK? " + pkcs7.Verify());
            return(pkcs7);
        }
예제 #15
0
        internal static void BasicCheckSignedDoc(String filePath, String signatureName)
        {
            PdfDocument   outDocument   = new PdfDocument(new PdfReader(filePath));
            SignatureUtil sigUtil       = new SignatureUtil(outDocument);
            PdfPKCS7      signatureData = sigUtil.ReadSignatureData(signatureName);

            NUnit.Framework.Assert.IsTrue(signatureData.VerifySignatureIntegrityAndAuthenticity());
            outDocument.Close();
        }
        public ActionResult Complete(SignatureCompleteModel model)
        {
            byte[] signedPdf;

            try {
                // Recover session data from Index action
                var sessionModel = Session["ITextSessionModel"] as ITextSessionModel;
                if (sessionModel == null)
                {
                    // This should not happen
                    return(RedirectToAction("Index"));
                }

                // Decode Certificate
                var certificate = new X509CertificateParser().ReadCertificate(model.CertContent);

                // Compute the external digest
                var pkcs7 = new PdfPKCS7(null, new X509Certificate[] { certificate }, DigestAlgorithm, false);
                pkcs7.SetExternalDigest(model.Signature, null, "RSA");

                // Get a padded PKCS#7
                byte[] pkcs7Encoded = pkcs7.GetEncodedPKCS7(sessionModel.RangeDigest);
                if (pkcs7Encoded.Length > 8192)                   // It shouldn't happen
                {
                    throw new InvalidOperationException("PKCS37 encoded shouldn't be bigger than the space reserved for it");
                }
                byte[] pkcs7Padded = new byte[8192];
                pkcs7Encoded.CopyTo(pkcs7Padded, 0);

                // Instanciate a PDF dictionary
                var sigDictionary = new PdfDictionary();
                // Write the PKCS#7 padded on the signature dictionary
                sigDictionary.Put(PdfName.CONTENTS, new PdfString(pkcs7Padded).SetHexWriting(true));
                // Finally, close the PDF appearance to finish the signature process
                sessionModel.SignatureApperance.Close(sigDictionary);

                // Receive the signed PDF bytes from the its stream, which was storage by the session variable
                signedPdf = sessionModel.SignedPdfStream.ToArray();

                // Close the signed PDF stream
                sessionModel.SignedPdfStream.Close();
            } catch (Exception ex) {
                ModelState.AddModelError("", ex.ToString());
                return(View());
            } finally {
                // Clear the object stored on the Session
                Session.Remove("SignatureCompleteModel");
            }

            TempData["SignatureInfoModel"] = new SignatureInfoModel()
            {
                File = Storage.StoreFile(signedPdf, ".pdf")
            };

            return(RedirectToAction("SignatureInfo"));
        }
예제 #17
0
        public PdfPKCS7 VerifySignature(SignatureUtil signUtil, String name)
        {
            PdfPKCS7 pkcs7 = signUtil.ReadSignatureData(name);

            Console.Out.WriteLine("Signature covers whole document: " + signUtil.SignatureCoversWholeDocument(name));
            Console.Out.WriteLine("Document revision: " + signUtil.GetRevision(name) + " of "
                                  + signUtil.GetTotalRevisions());
            Console.Out.WriteLine("Integrity check OK? " + pkcs7.VerifySignatureIntegrityAndAuthenticity());
            return(pkcs7);
        }
예제 #18
0
        public static void CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
        {
            List <BasicOcspResp> ocsps = new List <BasicOcspResp>();

            if (pkcs7.Ocsp != null)
            {
                ocsps.Add(pkcs7.Ocsp);
            }
            OcspVerifier          ocspVerifier = new OcspVerifier(null, ocsps);
            List <VerificationOK> verification =
                ocspVerifier.Verify(signCert, issuerCert, date);

            if (verification.Count == 0)
            {
                List <X509Crl> crls = new List <X509Crl>();
                if (pkcs7.CRLs != null)
                {
                    foreach (X509Crl crl in pkcs7.CRLs)
                    {
                        crls.Add(crl);
                    }
                }
                CrlVerifier crlVerifier = new CrlVerifier(null, crls);
                verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
            }
            if (verification.Count == 0)
            {
                Console.WriteLine("The signing certificate couldn't be verified with the example");
            }
            else
            {
                foreach (VerificationOK v in verification)
                {
                    Console.WriteLine(v);
                }
            }


            //Code not in the example, added by me
            //This way, I can find out if the certificate is revoked or not (through CRL). Not sure if it's the right way though
            if (verification.Count == 0 && pkcs7.CRLs != null && pkcs7.CRLs.Count != 0)
            {
                bool revoked = false;
                foreach (X509Crl crl in pkcs7.CRLs)
                {
                    revoked = crl.IsRevoked(pkcs7.SigningCertificate);
                    if (revoked)
                    {
                        break;
                    }
                }

                Console.WriteLine("Is certificate revoked?: " + revoked.ToString());
            }
        }
예제 #19
0
        private void AssertSignatureDetails(string signatureName,
                                            string expectedSignName, string expectedLocation, string expectedReason)
        {
            AcroFields fields = this.pdfReader.AcroFields;
            PdfPKCS7   pk     = fields.VerifySignature(signatureName);

            Assert.AreEqual(expectedSignName, CertificateInfo.GetSubjectFields(pk.SigningCertificate).GetField("CN"));
            Assert.AreEqual(expectedLocation, pk.Location);
            Assert.AreEqual(expectedReason, pk.Reason);
            Assert.That(pk.SignDate, Is.EqualTo(DateTime.Now).Within(1).Minutes);
        }
예제 #20
0
        public static (PdfPKCS7, FileDetailsModel) VerifySignature(FileDetailsModel model, SignatureUtil signUtil, String name)
        {
            PdfPKCS7 pkcs7 = signUtil.ReadSignatureData(name);

            logger.Error("Signature covers whole document: " + signUtil.SignatureCoversWholeDocument(name));
            logger.Error("Document revision: " + signUtil.GetRevision(name) + " of "
                         + signUtil.GetTotalRevisions());
            logger.Error("Integrity check OK? " + pkcs7.VerifySignatureIntegrityAndAuthenticity());
            model.Integrity = pkcs7.VerifySignatureIntegrityAndAuthenticity() == true?"OK":"NOT OK";
            return(pkcs7, model);
        }
예제 #21
0
        public virtual void TestSWA01()
        {
            String        filePath      = sourceFolder + "siwa.pdf";
            String        signatureName = "Signature1";
            PdfDocument   document      = new PdfDocument(new PdfReader(filePath));
            SignatureUtil sigUtil       = new SignatureUtil(document);
            PdfPKCS7      pdfPKCS7      = sigUtil.ReadSignatureData(signatureName);

            NUnit.Framework.Assert.IsTrue(pdfPKCS7.VerifySignatureIntegrityAndAuthenticity());
            NUnit.Framework.Assert.IsFalse(sigUtil.SignatureCoversWholeDocument(signatureName));
            document.Close();
        }
        public PdfPKCS7 VerifySignature(SignatureUtil signUtil, String name)
        {
            PdfPKCS7 pkcs7 = GetSignatureData(signUtil, name);

            X509Certificate[] certs = pkcs7.GetSignCertificateChain();

            // Timestamp is a secure source of signature creation time,
            // because it's based on Time Stamping Authority service.
            DateTime cal = pkcs7.GetTimeStampDate();


            // If there is no timestamp, use the current date
            if (TimestampConstants.UNDEFINED_TIMESTAMP_DATE == cal)
            {
                cal = new DateTime();
            }

            // Check if the certificate chain, presented in the PDF, can be verified against
            // the created key store.
            IList <VerificationException> errors = CertificateVerification.VerifyCertificates(certs, ks, cal);

            if (errors.Count == 0)
            {
                OUT_STREAM.WriteLine("Certificates verified against the KeyStore");
            }
            else
            {
                OUT_STREAM.WriteLine(errors);
            }

            // Find out if certificates were valid on the signing date, and if they are still valid today
            for (int i = 0; i < certs.Length; i++)
            {
                X509Certificate cert = (X509Certificate)certs[i];
                OUT_STREAM.WriteLine("=== Certificate " + i + " ===");
                ShowCertificateInfo(cert, cal.ToUniversalTime());
            }

            // Take the signing certificate
            X509Certificate signCert = (X509Certificate)certs[0];

            // Take the certificate of the issuer of that certificate (or null if it was self-signed).
            X509Certificate issuerCert = (certs.Length > 1 ? (X509Certificate)certs[1] : null);

            OUT_STREAM.WriteLine("=== Checking validity of the document at the time of signing ===");
            CheckRevocation(pkcs7, signCert, issuerCert, cal.ToUniversalTime());

            OUT_STREAM.WriteLine("=== Checking validity of the document today ===");
            CheckRevocation(pkcs7, signCert, issuerCert, new DateTime());

            return(pkcs7);
        }
예제 #23
0
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        protected internal virtual void InitLtvVerifier(PdfDocument document)
        {
            this.document = document;
            this.acroForm = PdfAcroForm.GetAcroForm(document, true);
            this.sgnUtil  = new SignatureUtil(document);
            IList <String> names = sgnUtil.GetSignatureNames();

            signatureName = names[names.Count - 1];
            this.signDate = DateTimeUtil.GetCurrentUtcTime();
            pkcs7         = CoversWholeDocument();
            LOGGER.Info(MessageFormatUtil.Format("Checking {0}signature {1}", pkcs7.IsTsp() ? "document-level timestamp "
                 : "", signatureName));
        }
예제 #24
0
        private Nenshkrim MerrNenshkrimInfo(AcroFields af, string name)
        {
            PdfPKCS7 pkcs7 = af.VerifySignature(name);

            var certificate = new X509Certificate2();

            var cert = (Org.BouncyCastle.X509.X509Certificate)pkcs7.Certificates[0];

            certificate.Import(cert.GetEncoded());
            Nenshkrim nenshkruesi = new Nenshkrim();

            nenshkruesi.Nenshkruesi = CertificateInfo.GetSubjectFields(cert).GetField("CN");

            string issuer = certificate.Issuer;

            nenshkruesi.IssuerCN = GetIssuer(issuer, "CN=");
            nenshkruesi.IssuerOU = GetIssuer(issuer, "OU=");
            nenshkruesi.IssuerO  = GetIssuer(issuer, "O=");
            nenshkruesi.IssuerC  = GetIssuer(issuer, "C=");

            if (nenshkruesi.IssuerC == "KS")
            {
                //largimi i [EMAIL] prej cn
                nenshkruesi.Nenshkruesi = nenshkruesi.Nenshkruesi.Substring(8);
            }

            nenshkruesi.Emri    = CertificateInfo.GetSubjectFields(cert).GetField("GIVENNAME");
            nenshkruesi.Mbiemri = CertificateInfo.GetSubjectFields(cert).GetField("SURNAME");
            //algoritmi hash
            nenshkruesi.AlgoritmiHash = pkcs7.GetHashAlgorithm();
            //algoritmi hash
            nenshkruesi.AlgoritmiEnkriptimit = pkcs7.GetEncryptionAlgorithm();
            //data e nenshrimit
            nenshkruesi.DataNenshkrimit = pkcs7.SignDate;
            //certifikata valide prej, deri
            nenshkruesi.CertifikataValidePrej = certificate.GetEffectiveDateString();
            nenshkruesi.CertifikataValideDeri = certificate.GetExpirationDateString();
            nenshkruesi.SerialNumber          = certificate.SerialNumber;

            //verifikimi
            if (pkcs7.Verify())
            {
                nenshkruesi.Valid = true;
            }
            else
            {
                nenshkruesi.Valid = false;
            }

            return(nenshkruesi);
        }
예제 #25
0
        public PdfSignInfo(PdfPKCS7 pkcs7)
        {
            SignType = SignTypes.PAdES.ToString();
            SignDate = pkcs7.SignDate;
            Reason   = pkcs7.Reason;
            try
            {
                IsVerified = pkcs7.Verify();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Verifica validità fallita: {0}", ex.Message));
            }

            Certificate = new SigningCertificate()
            {
                SerialNumber = pkcs7.SigningCertificate.SerialNumber.IntValue.ToString("X"),
                NotBefore    = pkcs7.SigningCertificate.NotBefore,
                NotAfter     = pkcs7.SigningCertificate.NotAfter
            };

            var issuerFields = CertificateInfo.GetIssuerFields(pkcs7.SigningCertificate);

            Certificate.Issuer = new IssuerDN()
            {
                SerialNumber     = issuerFields.GetField("SN"),
                Organization     = issuerFields.GetField("O"),
                OrganizationUnit = issuerFields.GetField("OU")
            };

            var subjectFields = CertificateInfo.GetSubjectFields(pkcs7.SigningCertificate);

            Certificate.Subject = new SubjectDN()
            {
                SerialNumber = subjectFields.GetField("SN"),
                GivenName    = subjectFields.GetField("GIVENNAME"),
                Surname      = subjectFields.GetField("SURNAME"),
                CommonName   = subjectFields.GetField("CN"),
                Organization = subjectFields.GetField("O")
            };

            if (pkcs7.TimeStampToken != null)
            {
                Children = new List <SignInfo>()
                {
                    new TsSignInfo(pkcs7)
                }
            }
            ;
        }
    }
        /// <summary>
        /// Verifies integrity of all PDF signatures
        /// </summary>
        /// <param name="path">Path to the PDF document that should be verified</param>
        /// <returns>Number of PDF signatures verified</returns>
        private static int VerifySignatureIntegrity(string path)
        {
            using (PdfReader reader = new PdfReader(path))
            {
                List <string> signatureNames = reader.AcroFields.GetSignatureNames();
                foreach (string signatureName in signatureNames)
                {
                    PdfPKCS7 pdfPkcs7 = reader.AcroFields.VerifySignature(signatureName);
                    Assert.IsTrue(pdfPkcs7.Verify());
                }

                return(signatureNames.Count);
            }
        }
예제 #27
0
            public byte[] Sign(Stream data)
            {
                PrivateKeySignature signature = new PrivateKeySignature(pk.Key, "SHA256");
                String   hashAlgorithm        = signature.GetHashAlgorithm();
                PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false);

                byte[]   hash        = DigestAlgorithms.Digest(data, hashAlgorithm);
                DateTime signingTime = DateTime.Now;

                byte[] sh           = sgn.getAuthenticatedAttributeBytes(hash, signingTime, null, null, CryptoStandard.CMS);
                byte[] extSignature = signature.Sign(sh);
                sgn.SetExternalDigest(extSignature, null, signature.GetEncryptionAlgorithm());
                return(sgn.GetEncodedPKCS7(hash, signingTime, null, null, null, CryptoStandard.CMS));
            }
        static byte[] GetCertificateChainOCSP(X509Certificate[] certificateChain)
        {
            byte[] ocsp = null;

            if (certificateChain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(certificateChain[0]);
                if (url != null && url.Length > 0)
                {
                    ocsp = new OcspClientBouncyCastle(certificateChain[0], certificateChain[1], url).GetEncoded();
                }
            }
            return(ocsp);
        }
예제 #29
0
        /// <summary>
        /// Prepares an
        /// <see cref="PdfPKCS7"/>
        /// instance for the given signature.
        /// This method handles signature parsing and might throw an exception if
        /// signature is malformed.
        /// <p>
        /// The returned
        /// <see cref="PdfPKCS7"/>
        /// can be used to fetch additional info about the signature
        /// and also to perform integrity check of data signed by the given signature field.
        /// </p>
        /// Prepared
        /// <see cref="PdfPKCS7"/>
        /// instance calculates digest based on signature's /ByteRange entry.
        /// In order to check that /ByteRange is properly defined and given signature indeed covers the current PDF document
        /// revision please use
        /// <see cref="SignatureCoversWholeDocument(System.String)"/>
        /// method.
        /// </summary>
        /// <param name="signatureFieldName">the signature field name</param>
        /// <param name="securityProvider">the security provider or null for the default provider</param>
        /// <returns>
        /// a
        /// <see cref="PdfPKCS7"/>
        /// instance which can be used to fetch additional info about the signature
        /// and also to perform integrity check of data signed by the given signature field.
        /// </returns>
        public virtual PdfPKCS7 ReadSignatureData(String signatureFieldName)
        {
            PdfSignature signature = GetSignature(signatureFieldName);

            if (signature == null)
            {
                return(null);
            }
            try {
                PdfName   sub      = signature.GetSubFilter();
                PdfString contents = signature.GetContents();
                PdfPKCS7  pk       = null;
                if (sub.Equals(PdfName.Adbe_x509_rsa_sha1))
                {
                    PdfString cert = signature.GetPdfObject().GetAsString(PdfName.Cert);
                    if (cert == null)
                    {
                        cert = signature.GetPdfObject().GetAsArray(PdfName.Cert).GetAsString(0);
                    }
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), cert.GetValueBytes());
                }
                else
                {
                    pk = new PdfPKCS7(PdfEncodings.ConvertToBytes(contents.GetValue(), null), sub);
                }
                UpdateByteRange(pk, signature);
                PdfString date = signature.GetDate();
                if (date != null)
                {
                    pk.SetSignDate(PdfDate.Decode(date.ToString()));
                }
                String signName = signature.GetName();
                pk.SetSignName(signName);
                String reason = signature.GetReason();
                if (reason != null)
                {
                    pk.SetReason(reason);
                }
                String location = signature.GetLocation();
                if (location != null)
                {
                    pk.SetLocation(location);
                }
                return(pk);
            }
            catch (Exception e) {
                throw new PdfException(e);
            }
        }
예제 #30
0
파일: X509Utils.cs 프로젝트: tixsys/esteid
        static public string GetIssuerFields(byte[] cert, string field)
        {
            Org.BouncyCastle.X509.X509CertificateParser cp    = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate[]     chain = new Org.BouncyCastle.X509.X509Certificate[]
            {
                cp.ReadCertificate(cert)
            };

            if (chain[0] != null)
            {
                return(PdfPKCS7.GetIssuerFields(chain[0]).GetField(field));
            }

            return(string.Empty);
        }
예제 #31
0
        private void VerifySignatures(SignatureUtil signUtil, IList <String> names)
        {
            foreach (String name in names)
            {
                PdfPKCS7 pkcs7 = signUtil.ReadSignatureData(name);

                // verify signature integrity
                if (!pkcs7.VerifySignatureIntegrityAndAuthenticity())
                {
                    AddError(String.Format("\"{0}\" signature integrity is invalid\n", name));
                }

                VerifyCertificates(pkcs7);
            }
        }
예제 #32
0
	    public static void CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date) {
		    List<BasicOcspResp> ocsps = new List<BasicOcspResp>();
		    if (pkcs7.Ocsp != null)
			    ocsps.Add(pkcs7.Ocsp);
		    OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
		    List<VerificationOK> verification =
			    ocspVerifier.Verify(signCert, issuerCert, date);
		    if (verification.Count == 0) {
			    List<X509Crl> crls = new List<X509Crl>();
			    if (pkcs7.CRLs != null)
				    foreach (X509Crl crl in pkcs7.CRLs)
					    crls.Add(crl);
			    CrlVerifier crlVerifier = new CrlVerifier(null, crls);
			    verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
		    }
		    if (verification.Count == 0)
			    Console.WriteLine("The signing certificate couldn't be verified");
		    else
			    foreach (VerificationOK v in verification)
				    Console.WriteLine(v);
	    }
        private static bool CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
        {
            List<BasicOcspResp> ocsps = new List<BasicOcspResp>();
            if (pkcs7.Ocsp != null)
                ocsps.Add(pkcs7.Ocsp);
            OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
            List<VerificationOK> verification =
                ocspVerifier.Verify(signCert, issuerCert, date);
            if (verification.Count == 0)
            {
                List<X509Crl> crls = new List<X509Crl>();
                if (pkcs7.CRLs != null)
                    foreach (X509Crl crl in pkcs7.CRLs)
                        crls.Add(crl);

                if (crls.Count > 0)
                {
                    CrlVerifier crlVerifier = new CrlVerifier(null, crls);
                    verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
                }

            }
            if (verification.Count == 0)
                return false;
            else
                foreach (VerificationOK v in verification)
                    Console.WriteLine(v);

            return (verification.Count > 0);
        }