Ejemplo n.º 1
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Operator.OperatorCreationException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        public virtual bool VerifyAuthorizedOCSPResponderTest(DateTime ocspResponderCertStartDate, DateTime ocspResponderCertEndDate
                                                              , DateTime checkDate)
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "intermediateRsa.p12"
                                                                                      , password)[0];
            ICipherParameters caPrivateKey = Pkcs12FileHelper.ReadFirstKey(certsSrc + "intermediateRsa.p12", password,
                                                                           password);
            String          checkCertFileName = certsSrc + "signCertRsaWithChain.p12";
            X509Certificate checkCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
                0];
            RsaKeyPairGenerator     keyGen             = SignTestPortUtil.BuildRSA2048KeyPairGenerator();
            AsymmetricCipherKeyPair key                = keyGen.GenerateKeyPair();
            ICipherParameters       ocspRespPrivateKey = key.Private;
            AsymmetricKeyParameter  ocspRespPublicKey  = key.Public;
            TestCertificateBuilder  certBuilder        = new TestCertificateBuilder(ocspRespPublicKey, caCert, caPrivateKey, "CN=iTextTestOCSPResponder, OU=test, O=iText"
                                                                                    );

            certBuilder.SetStartDate(ocspResponderCertStartDate);
            certBuilder.SetEndDate(ocspResponderCertEndDate);
            X509Certificate         ocspResponderCert = certBuilder.BuildAuthorizedOCSPResponderCert();
            TestOcspResponseBuilder builder           = new TestOcspResponseBuilder(ocspResponderCert, ocspRespPrivateKey);
            TestOcspClient          ocspClient        = new TestOcspClient().AddBuilderForCertIssuer(caCert, builder);

            byte[]        basicOcspRespBytes = ocspClient.GetEncoded(checkCert, caCert, null);
            Asn1Object    var2          = Asn1Object.FromByteArray(basicOcspRespBytes);
            BasicOcspResp basicOCSPResp = new BasicOcspResp(BasicOcspResponse.GetInstance(var2));
            OCSPVerifier  ocspVerifier  = new OCSPVerifier(null, null);

            return(ocspVerifier.Verify(basicOCSPResp, checkCert, caCert, checkDate));
        }
Ejemplo n.º 2
0
        public virtual void LtvEnabledSingleSignatureTest01()
        {
            String signCertFileName         = certsSrc + "signCertRsaWithChain.p12";
            String tsaCertFileName          = certsSrc + "tsCertRsa.p12";
            String intermediateCertFileName = certsSrc + "intermediateRsa.p12";
            String caCertFileName           = certsSrc + "rootRsa.p12";
            String srcFileName = sourceFolder + "helloWorldDoc.pdf";
            String ltvFileName = destinationFolder + "ltvEnabledSingleSignatureTest01.pdf";

            X509Certificate[] tsaChain         = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey    = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            X509Certificate   intermediateCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(intermediateCertFileName
                                                                                                  , password)[0];
            ICipherParameters intermediatePrivateKey = Pkcs12FileHelper.ReadFirstKey(intermediateCertFileName, password
                                                                                     , password);
            X509Certificate   caCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey   = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestTsaClient     testTsa        = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);
            TestOcspClient    testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(intermediateCert, intermediatePrivateKey
                                                                                            ).AddBuilderForCertIssuer(caCert, caPrivateKey);

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(ltvFileName, FileMode.Create),
                                                              new StampingProperties());

            signer.SetFieldName("Signature1");
            signer.SignDetached(pks, signChain, null, testOcspClient, testTsa, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(destinationFolder + "ltvEnabledSingleSignatureTest01.pdf", "Signature1");
        }
Ejemplo n.º 3
0
        public virtual void LtvEnabledTest01()
        {
            String tsaCertFileName = certsSrc + "tsCertRsa.p12";
            String caCertFileName  = certsSrc + "rootRsa.p12";
            String srcFileName     = sourceFolder + "signedDoc.pdf";
            String ltvFileName     = destinationFolder + "ltvEnabledTest01.pdf";
            String ltvTsFileName   = destinationFolder + "ltvEnabledTsTest01.pdf";

            X509Certificate[] tsaChain       = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey  = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            X509Certificate   caCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey   = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestTsaClient     testTsa        = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);
            TestOcspClient    testOcspClient = new TestOcspClient().AddBuilderForCertIssuer(caCert, caPrivateKey);
            TestCrlClient     testCrlClient  = new TestCrlClient(caCert, caPrivateKey);
            PdfDocument       document       = new PdfDocument(new PdfReader(srcFileName), new PdfWriter(ltvFileName), new StampingProperties
                                                                   ().UseAppendMode());
            LtvVerification ltvVerification = new LtvVerification(document);

            ltvVerification.AddVerification("Signature1", testOcspClient, testCrlClient, LtvVerification.CertificateOption
                                            .SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.YES);
            ltvVerification.Merge();
            document.Close();
            PdfSigner signer = new PdfSigner(new PdfReader(ltvFileName), new FileStream(ltvTsFileName, FileMode.Create
                                                                                        ), new StampingProperties().UseAppendMode());

            signer.Timestamp(testTsa, "timestampSig1");
            BasicCheckLtvDoc("ltvEnabledTsTest01.pdf", "timestampSig1");
        }
Ejemplo n.º 4
0
        public virtual void ValidOcspTest01()
        {
            X509Certificate         caCert       = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters       caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestOcspResponseBuilder builder      = new TestOcspResponseBuilder(caCert, caPrivateKey);

            NUnit.Framework.Assert.IsTrue(VerifyTest(builder));
        }
Ejemplo n.º 5
0
        public virtual void ValidOcspTest01()
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password
                                                                                      )[0];
            TestOcspResponseBuilder builder = new TestOcspResponseBuilder(caCert);

            NUnit.Framework.Assert.IsTrue(VerifyTest(builder));
        }
Ejemplo n.º 6
0
        public virtual void ValidCrl01()
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password
                                                                                      )[0];
            TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-1));

            NUnit.Framework.Assert.IsTrue(VerifyTest(crlBuilder));
        }
Ejemplo n.º 7
0
 void LoadConfiguration()
 {
     DownloadCertificate()
     .ContinueWith(certificateTask => {
         if (!certificateTask.IsFaulted && certificateTask.Result != null)
         {
             DialogHelper.AskForPassword(AppResources.INPUT_PKCS12_PASSWORD, AppResources.CONFIGURATION_TITLE).ContinueWith(
                 senhaTask => {
                 if (!senhaTask.IsFaulted)
                 {
                     try
                     {
                         Stream certificate = certificateTask.Result;
                         if (VerifyCertificate(certificate, senhaTask.Result))
                         {
                             Pkcs12FileHelper.Save(certificate).ContinueWith(saveTask => {
                                 if (!saveTask.IsFaulted)
                                 {
                                     Application.Current.Properties[Const.CONFIG_OK]      = true;
                                     Application.Current.Properties[Const.CONFIG_VERSION] = Const.CONFIG_VALUE_CURRENT_VERSION;
                                     Application.Current.SavePropertiesAsync().Wait();
                                     //Sends the current gcm token to the server if it exists
                                     SendNotificationToken().Wait();
                                     OpenDocumentListPage();
                                 }
                                 else
                                 {
                                     ShowErrorMessage(ExceptionHelper.GetMessage(AppResources.CERTIFICATE_SAVE_ERROR, saveTask.Exception.InnerException),
                                                      () => Application.Current.MainPage = new LoginPage());
                                 }
                             });
                         }
                     }
                     catch (IOException)
                     {
                         //probably a wrong pkcs12 password was supplied. Try again.
                         ShowErrorMessage(AppResources.WRONG_PKCS12_PASSWORD, () => LoadConfiguration());
                     }
                     catch (Exception e)
                     {
                         string errorMsg = ExceptionHelper.GetMessage(AppResources.WRONG_PKCS12_PASSWORD, e);
                         ShowErrorMessage(errorMsg, () => Application.Current.MainPage = new LoginPage());
                     }
                 }
                 else
                 {
                     string errorMsg = ExceptionHelper.GetMessage(AppResources.ASK_PASSWORD_ERROR, senhaTask.Exception.InnerException);
                     ShowErrorMessage(errorMsg, () => Application.Current.MainPage = new LoginPage());
                 }
             });
         }
         else
         {
             string errorMsg = ExceptionHelper.GetMessage(AppResources.CERTIFICATE_LOAD_ERROR, certificateTask.Exception.InnerException);
             ShowErrorMessage(errorMsg, () => Application.Current.MainPage = new LoginPage());
         }
     });
 }
Ejemplo n.º 8
0
        public virtual void InvalidUnknownOcspTest01()
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password
                                                                                      )[0];
            TestOcspResponseBuilder builder = new TestOcspResponseBuilder(caCert);

            builder.SetCertificateStatus(new UnknownStatus());
            NUnit.Framework.Assert.IsFalse(VerifyTest(builder));
        }
Ejemplo n.º 9
0
        public virtual void InvalidRevokedOcspTest01()
        {
            X509Certificate         caCert       = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters       caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestOcspResponseBuilder builder      = new TestOcspResponseBuilder(caCert, caPrivateKey);

            builder.SetCertificateStatus(new RevokedStatus(DateTimeUtil.GetCurrentUtcTime().AddDays(-20), Org.BouncyCastle.Asn1.X509.CrlReason.KeyCompromise
                                                           ));
            NUnit.Framework.Assert.IsFalse(VerifyTest(builder));
        }
Ejemplo n.º 10
0
        public virtual void ExpiredIssuerCertTest01()
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "intermediateExpiredCert.p12"
                                                                                      , password)[0];
            ICipherParameters caPrivateKey = Pkcs12FileHelper.ReadFirstKey(certsSrc + "intermediateExpiredCert.p12", password
                                                                           , password);
            TestOcspResponseBuilder builder = new TestOcspResponseBuilder(caCert, caPrivateKey);

            NUnit.Framework.Assert.IsTrue(VerifyTest(builder, certsSrc + "signCertRsaWithExpiredChain.p12", caCert.NotBefore
                                                     ));
        }
        public virtual void ValidCertificateChain01()
        {
            X509Certificate[] certChain = Pkcs12FileHelper.ReadFirstChain(certsSrc + "signCertRsaWithChain.p12", password
                                                                          );
            String caCertFileName = certsSrc + "rootRsa.p12";
            List <X509Certificate>        caKeyStore             = Pkcs12FileHelper.InitStore(caCertFileName, password);
            IList <VerificationException> verificationExceptions = CertificateVerification.VerifyCertificates(certChain
                                                                                                              , caKeyStore);

            NUnit.Framework.Assert.IsTrue(verificationExceptions.IsEmpty());
        }
Ejemplo n.º 12
0
        public virtual void ValidLtvDocTest02()
        {
            String      ltvTsFileName = sourceFolder + "ltvDoc.pdf";
            LtvVerifier verifier      = new LtvVerifier(new PdfDocument(new PdfReader(ltvTsFileName)));

            verifier.SetCertificateOption(LtvVerification.CertificateOption.WHOLE_CHAIN);
            verifier.SetRootStore(Pkcs12FileHelper.InitStore(certsSrc + "rootStore.p12", password));
            IList <VerificationOK> verificationMessages = verifier.Verify(null);

            NUnit.Framework.Assert.AreEqual(7, verificationMessages.Count);
        }
Ejemplo n.º 13
0
        public virtual void InvalidOutdatedOcspTest01()
        {
            X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password
                                                                                      )[0];
            TestOcspResponseBuilder builder = new TestOcspResponseBuilder(caCert);
            DateTime thisUpdate             = DateTimeUtil.GetCurrentTime().AddDays(-30);
            DateTime nextUpdate             = DateTimeUtil.GetCurrentTime().AddDays(-15);

            builder.SetThisUpdate(thisUpdate);
            builder.SetNextUpdate(nextUpdate);
            NUnit.Framework.Assert.IsFalse(VerifyTest(builder));
        }
Ejemplo n.º 14
0
        public virtual void InvalidOutdatedOcspTest01()
        {
            X509Certificate         caCert       = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters       caPrivateKey = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestOcspResponseBuilder builder      = new TestOcspResponseBuilder(caCert, caPrivateKey);
            DateTime thisUpdate = DateTimeUtil.GetCurrentTime().AddDays(-30);
            DateTime nextUpdate = DateTimeUtil.GetCurrentTime().AddDays(-15);

            builder.SetThisUpdate(thisUpdate);
            builder.SetNextUpdate(nextUpdate);
            NUnit.Framework.Assert.IsFalse(VerifyTest(builder));
        }
Ejemplo n.º 15
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        private bool VerifyTest(TestOcspResponseBuilder rootRsaOcspBuilder, String checkCertFileName, DateTime checkDate
                                )
        {
            X509Certificate checkCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
                0];
            X509Certificate rootCert   = rootRsaOcspBuilder.GetIssuerCert();
            TestOcspClient  ocspClient = new TestOcspClient().AddBuilderForCertIssuer(rootCert, rootRsaOcspBuilder);

            byte[]        basicOcspRespBytes = ocspClient.GetEncoded(checkCert, rootCert, null);
            Asn1Object    var2          = Asn1Object.FromByteArray(basicOcspRespBytes);
            BasicOcspResp basicOCSPResp = new BasicOcspResp(BasicOcspResponse.GetInstance(var2));
            OCSPVerifier  ocspVerifier  = new OCSPVerifier(null, null);

            return(ocspVerifier.Verify(basicOCSPResp, checkCert, rootCert, checkDate));
        }
Ejemplo n.º 16
0
        public virtual void TimestampTest01()
        {
            String tsaCertFileName = certsSrc + "tsCertRsa.p12";
            String srcFileName     = sourceFolder + "helloWorldDoc.pdf";
            String outFileName     = destinationFolder + "timestampTest01.pdf";

            X509Certificate[] tsaChain      = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            PdfSigner         signer        = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                            false);
            TestTsaClient testTsa = new TestTsaClient(iText.IO.Util.JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);

            signer.Timestamp(testTsa, "timestampSig1");
            PadesSigTest.BasicCheckSignedDoc(destinationFolder + "timestampTest01.pdf", "timestampSig1");
        }
        public virtual void PadesSignatureLevelLTATest01()
        {
            String outFileName     = destinationFolder + "padesSignatureLevelLTATest01.pdf";
            String srcFileName     = sourceFolder + "signedPAdES-LT.pdf";
            String tsaCertFileName = certsSrc + "tsCertRsa.p12";

            X509Certificate[] tsaChain      = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            PdfSigner         signer        = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                            new StampingProperties().UseAppendMode());
            TestTsaClient testTsa = new TestTsaClient(JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);

            signer.Timestamp(testTsa, "timestampSig1");
            PadesSigTest.BasicCheckSignedDoc(destinationFolder + "padesSignatureLevelLTATest01.pdf", "timestampSig1");
        }
Ejemplo n.º 18
0
        public virtual void SignEncryptedDoc02()
        {
            String          fileName = "encrypted_cert.pdf";
            String          src      = sourceFolder + fileName;
            String          dest     = destinationFolder + "signed_" + fileName;
            X509Certificate cert     = CryptoUtil.ReadPublicCertificate(new FileStream(sourceFolder + "test.cer", FileMode.Open
                                                                                       , FileAccess.Read));
            ICipherParameters privateKey = Pkcs12FileHelper.ReadFirstKey(sourceFolder + "test.p12", password, password
                                                                         );
            PdfReader reader = new PdfReader(src, new ReaderProperties().SetPublicKeySecurityParams(cert, privateKey));
            PdfSigner signer = new PdfSigner(reader, new FileStream(dest, FileMode.Create), true);
            // Creating the signature
            IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256);

            signer.SignDetached(pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
        }
Ejemplo n.º 19
0
 public virtual void InvalidRevokedCrl01()
 {
     NUnit.Framework.Assert.That(() => {
         X509Certificate caCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(certsSrc + "rootRsa.p12", password
                                                                                   )[0];
         TestCrlBuilder crlBuilder = new TestCrlBuilder(caCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-1));
         String checkCertFileName  = certsSrc + "signCertRsa01.p12";
         X509Certificate checkCert = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
             0];
         crlBuilder.AddCrlEntry(checkCert, DateTimeUtil.GetCurrentUtcTime().AddDays(-40), Org.BouncyCastle.Asn1.X509.CrlReason.KeyCompromise
                                );
         VerifyTest(crlBuilder);
     }
                                 , NUnit.Framework.Throws.TypeOf <VerificationException>());
     ;
 }
Ejemplo n.º 20
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        private bool VerifyTest(TestOcspResponseBuilder builder)
        {
            String            caCertFileName    = certsSrc + "rootRsa.p12";
            String            checkCertFileName = certsSrc + "signCertRsa01.p12";
            X509Certificate   caCert            = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey      = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            X509Certificate   checkCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
                0];
            TestOcspClient ocspClient = new TestOcspClient(builder, caPrivateKey);

            byte[]        basicOcspRespBytes = ocspClient.GetEncoded(checkCert, caCert, null);
            Asn1Object    var2          = Asn1Object.FromByteArray(basicOcspRespBytes);
            BasicOcspResp basicOCSPResp = new BasicOcspResp(BasicOcspResponse.GetInstance(var2));
            OCSPVerifier  ocspVerifier  = new OCSPVerifier(null, null);

            return(ocspVerifier.Verify(basicOCSPResp, checkCert, caCert, DateTimeUtil.GetCurrentUtcTime()));
        }
Ejemplo n.º 21
0
        public virtual void CalcHashOnDocCreationThenDeferredSignTest01()
        {
            String input       = sourceFolder + "helloWorldDoc.pdf";
            String outFileName = destinationFolder + "calcHashOnDocCreationThenDeferredSignTest01.pdf";
            String cmpFileName = sourceFolder + "cmp_calcHashOnDocCreationThenDeferredSignTest01.pdf";
            // pre-calculate hash on creating pre-signed PDF
            String       sigFieldName  = "DeferredSignature1";
            PdfName      filter        = PdfName.Adobe_PPKLite;
            PdfName      subFilter     = PdfName.Adbe_pkcs7_detached;
            int          estimatedSize = 8192;
            PdfReader    reader        = new PdfReader(input);
            MemoryStream baos          = new MemoryStream();
            PdfSigner    signer        = new PdfSigner(reader, baos, new StampingProperties());

            signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetLayer2Text("Signature field which signing is deferred.").SetPageRect(new Rectangle(36, 600,
                                                                                                             200, 100)).SetPageNumber(1);
            signer.SetFieldName(sigFieldName);
            SignDeferredTest.DigestCalcBlankSigner external = new SignDeferredTest.DigestCalcBlankSigner(filter, subFilter
                                                                                                         );
            signer.SignExternalContainer(external, estimatedSize);
            byte[] docBytesHash   = external.GetDocBytesHash();
            byte[] preSignedBytes = baos.ToArray();
            // sign the hash
            String signCertFileName = certsSrc + "signCertRsa01.p12";

            X509Certificate[] signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);

            byte[] cmsSignature = SignDocBytesHash(docBytesHash, signPrivateKey, signChain);
            // fill the signature to the presigned document
            SignDeferredTest.ReadySignatureSigner extSigContainer = new SignDeferredTest.ReadySignatureSigner(cmsSignature
                                                                                                              );
            PdfDocument docToSign = new PdfDocument(new PdfReader(new MemoryStream(preSignedBytes)));
            FileStream  outStream = new FileStream(outFileName, FileMode.Create);

            PdfSigner.SignDeferred(docToSign, sigFieldName, outStream, extSigContainer);
            docToSign.Close();
            outStream.Dispose();
            // validate result
            PadesSigTest.BasicCheckSignedDoc(outFileName, sigFieldName);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outFileName, cmpFileName, destinationFolder
                                                                            , null));
        }
Ejemplo n.º 22
0
        private void Logout()
        {
            Task <bool> task = DialogHelper.ShowConfirm(AppResources.APP_TITLE, AppResources.LOGOUT_CONFIRM);

            task.ContinueWith(t =>
            {
                if (t.IsCompleted && t.Result)
                {
                    Application.Current.Properties[Const.CONFIG_API_KEY] = null;
                    Application.Current.SavePropertiesAsync().Wait();
                    Pkcs12FileHelper.DeleteFile();
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        Application.Current.MainPage = new LoginPage();
                    });
                }
            });
        }
        public virtual void SequentialSignOfFileWithAnnots()
        {
            String signCertFileName = certsSrc + "signCertRsa01.p12";
            String outFileName      = destinationFolder + "sequentialSignOfFileWithAnnots.pdf";
            String srcFileName      = sourceFolder + "signedWithAnnots.pdf";

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            String             signatureName  = "Signature2";
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                              new StampingProperties().UseAppendMode());

            signer.SetFieldName(signatureName);
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 350, 200, 100)).SetReason("Test").SetLocation
                ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText7.");
            signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(outFileName, signatureName);
        }
        public async Task CheckCertUpdate()
        {
            try
            {
                if (DeviceInfo.Connectivity.InternetReachability == NetworkReachability.NotReachable)
                {
                    return;
                }

                string certHash = await Pkcs12FileHelper.GetSha1Hash();

                if (certHash != null)
                {
                    string remoteHash = await GetRemoteCertificateHash();

                    if (remoteHash == null)
                    {
                        DialogHelper.ShowAlertOK(AppResources.APP_TITLE, AppResources.CERT_UPDATE_FAILED);
                        return;
                    }

                    if (!certHash.Equals(remoteHash, StringComparison.OrdinalIgnoreCase))
                    {
                        bool yes = await DialogHelper.ShowConfirm(AppResources.APP_TITLE, AppResources.CERT_UPDATE_AVAILABLE);

                        if (yes)
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                Application.Current.MainPage = new CertPage();
                            });
                        }
                    }
                    else
                    {
                        DialogHelper.ShowAlertOK(AppResources.APP_TITLE, AppResources.CERT_UPDATE_NOT_REQUIRED);
                    }
                }
            } catch (Exception)
            {
                DialogHelper.ShowAlertOK(AppResources.APP_TITLE, AppResources.CERT_UPDATE_FAILED);
            }
        }
Ejemplo n.º 25
0
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        private bool VerifyTest(TestCrlBuilder crlBuilder)
        {
            String            caCertFileName    = certsSrc + "rootRsa.p12";
            X509Certificate   caCert            = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey      = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            String            checkCertFileName = certsSrc + "signCertRsa01.p12";
            X509Certificate   checkCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(checkCertFileName, password)[
                0];
            TestCrlClient        crlClient          = new TestCrlClient(crlBuilder, caPrivateKey);
            ICollection <byte[]> crlBytesCollection = crlClient.GetEncoded(checkCert, null);
            bool verify = false;

            foreach (byte[] crlBytes in crlBytesCollection)
            {
                X509Crl     crl      = (X509Crl)SignTestPortUtil.ParseCrlFromStream(new MemoryStream(crlBytes));
                CRLVerifier verifier = new CRLVerifier(null, null);
                verify = verifier.Verify(crl, checkCert, caCert, DateTimeUtil.GetCurrentUtcTime());
                break;
            }
            return(verify);
        }
Ejemplo n.º 26
0
        public virtual void AddLtvInfo()
        {
            String tsaCertFileName = certsSrc + "tsCertRsa.p12";
            String caCertFileName  = certsSrc + "rootRsa.p12";
            String srcFileName     = sourceFolder + "signedDoc.pdf";
            String ltvFileName     = destinationFolder + "ltvEnabledTest01.pdf";
            String ltvFileName2    = destinationFolder + "ltvEnabledTest02.pdf";

            X509Certificate[] tsaChain       = Pkcs12FileHelper.ReadFirstChain(tsaCertFileName, password);
            ICipherParameters tsaPrivateKey  = Pkcs12FileHelper.ReadFirstKey(tsaCertFileName, password, password);
            X509Certificate   caCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey   = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            TestTsaClient     testTsa        = new TestTsaClient(iText.IO.Util.JavaUtil.ArraysAsList(tsaChain), tsaPrivateKey);
            TestOcspClient    testOcspClient = new TestOcspClient(caCert, caPrivateKey);
            TestCrlClient     testCrlClient  = new TestCrlClient(caCert, caPrivateKey);

            AddLtvInfo(srcFileName, ltvFileName, "sig", testOcspClient, testCrlClient);
            AddLtvInfo(ltvFileName, ltvFileName2, "sig2", testOcspClient, testCrlClient);
            PdfReader     reader            = new PdfReader(ltvFileName2);
            PdfDocument   document          = new PdfDocument(reader);
            PdfDictionary catalogDictionary = document.GetCatalog().GetPdfObject();
            PdfDictionary dssDictionary     = catalogDictionary.GetAsDictionary(PdfName.DSS);
            PdfDictionary vri = dssDictionary.GetAsDictionary(PdfName.VRI);

            NUnit.Framework.Assert.IsNotNull(vri);
            NUnit.Framework.Assert.AreEqual(2, vri.Size());
            PdfArray ocsps = dssDictionary.GetAsArray(PdfName.OCSPs);

            NUnit.Framework.Assert.IsNotNull(ocsps);
            NUnit.Framework.Assert.AreEqual(2, ocsps.Size());
            PdfArray certs = dssDictionary.GetAsArray(PdfName.Certs);

            NUnit.Framework.Assert.IsNotNull(certs);
            NUnit.Framework.Assert.AreEqual(2, certs.Size());
            PdfArray crls = dssDictionary.GetAsArray(PdfName.CRLs);

            NUnit.Framework.Assert.IsNotNull(crls);
            NUnit.Framework.Assert.AreEqual(1, crls.Size());
        }
Ejemplo n.º 27
0
        public virtual void AddLtvInfo()
        {
            String            caCertFileName    = certsSrc + "rootRsa.p12";
            String            interCertFileName = certsSrc + "intermediateRsa.p12";
            String            srcFileName       = sourceFolder + "signedTwice.pdf";
            String            ltvFileName       = destinationFolder + "ltvEnabledTest01.pdf";
            String            ltvFileName2      = destinationFolder + "ltvEnabledTest02.pdf";
            X509Certificate   caCert            = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(caCertFileName, password)[0];
            ICipherParameters caPrivateKey      = Pkcs12FileHelper.ReadFirstKey(caCertFileName, password, password);
            X509Certificate   interCert         = (X509Certificate)Pkcs12FileHelper.ReadFirstChain(interCertFileName, password)[
                0];
            ICipherParameters interPrivateKey = Pkcs12FileHelper.ReadFirstKey(interCertFileName, password, password);
            TestOcspClient    testOcspClient  = new TestOcspClient().AddBuilderForCertIssuer(interCert, interPrivateKey).AddBuilderForCertIssuer
                                                    (caCert, caPrivateKey);
            TestCrlClient testCrlClient = new TestCrlClient(caCert, caPrivateKey);

            AddLtvInfo(srcFileName, ltvFileName, "Signature1", testOcspClient, testCrlClient);
            AddLtvInfo(ltvFileName, ltvFileName2, "Signature2", testOcspClient, testCrlClient);
            PdfReader     reader            = new PdfReader(ltvFileName2);
            PdfDocument   document          = new PdfDocument(reader);
            PdfDictionary catalogDictionary = document.GetCatalog().GetPdfObject();
            PdfDictionary dssDictionary     = catalogDictionary.GetAsDictionary(PdfName.DSS);
            PdfDictionary vri = dssDictionary.GetAsDictionary(PdfName.VRI);

            NUnit.Framework.Assert.IsNotNull(vri);
            NUnit.Framework.Assert.AreEqual(2, vri.Size());
            PdfArray ocsps = dssDictionary.GetAsArray(PdfName.OCSPs);

            NUnit.Framework.Assert.IsNotNull(ocsps);
            NUnit.Framework.Assert.AreEqual(5, ocsps.Size());
            PdfArray certs = dssDictionary.GetAsArray(PdfName.Certs);

            NUnit.Framework.Assert.IsNotNull(certs);
            NUnit.Framework.Assert.AreEqual(5, certs.Size());
            PdfArray crls = dssDictionary.GetAsArray(PdfName.CRLs);

            NUnit.Framework.Assert.IsNotNull(crls);
            NUnit.Framework.Assert.AreEqual(2, crls.Size());
        }
        public virtual void SecondSignOfTaggedDocTest()
        {
            String signCertFileName = certsSrc + "signCertRsa01.p12";
            String outFileName      = destinationFolder + "secondSignOfTagged.pdf";
            String srcFileName      = sourceFolder + "taggedAndSignedDoc.pdf";

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            String             signatureName  = "Signature2";
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                              new StampingProperties().UseAppendMode());
            PdfDocument document = signer.GetDocument();

            document.GetWriter().SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            signer.SetFieldName(signatureName);
            PdfSignatureAppearance appearance = signer.GetSignatureAppearance();

            appearance.SetPageNumber(1);
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 550, 200, 100)).SetReason("Test2").SetLocation
                ("TestCity2").SetLayer2Text("Approval test signature #2.\nCreated by iText7.");
            signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature1");
            PadesSigTest.BasicCheckSignedDoc(outFileName, "Signature2");
            using (PdfDocument twiceSigned = new PdfDocument(new PdfReader(outFileName))) {
                using (PdfDocument resource = new PdfDocument(new PdfReader(srcFileName))) {
                    float resourceStrElemNumber = resource.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                      (0).GetAsArray(PdfName.K).Size();
                    float outStrElemNumber = twiceSigned.GetStructTreeRoot().GetPdfObject().GetAsArray(PdfName.K).GetAsDictionary
                                                 (0).GetAsArray(PdfName.K).Size();
                    // Here we assert the amount of objects in StructTreeRoot in resource file and twice signed file
                    // as the original signature validation failed by Adobe because of struct tree change. If the fix
                    // would make this tree unchanged, then the assertion should be adjusted with comparing the tree of
                    // objects in StructTreeRoot to ensure that it won't be changed.
                    NUnit.Framework.Assert.AreNotEqual(resourceStrElemNumber, outStrElemNumber);
                }
            }
        }
Ejemplo n.º 29
0
        public virtual void DeferredHashCalcAndSignTest01()
        {
            String srcFileName      = sourceFolder + "templateForSignCMSDeferred.pdf";
            String outFileName      = destinationFolder + "deferredHashCalcAndSignTest01.pdf";
            String cmpFileName      = sourceFolder + "cmp_deferredHashCalcAndSignTest01.pdf";
            String signCertFileName = certsSrc + "signCertRsa01.p12";

            X509Certificate[]           signChain       = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters           signPrivateKey  = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignatureContainer extSigContainer = new SignDeferredTest.CmsDeferredSigner(signPrivateKey, signChain
                                                                                                 );
            String      sigFieldName = "DeferredSignature1";
            PdfDocument docToSign    = new PdfDocument(new PdfReader(srcFileName));
            FileStream  outStream    = new FileStream(outFileName, FileMode.Create);

            PdfSigner.SignDeferred(docToSign, sigFieldName, outStream, extSigContainer);
            docToSign.Close();
            outStream.Dispose();
            // validate result
            PadesSigTest.BasicCheckSignedDoc(outFileName, sigFieldName);
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareVisually(outFileName, cmpFileName, destinationFolder
                                                                            , null));
        }
Ejemplo n.º 30
0
        private void SignApproval(String signCertFileName, String outFileName, SignaturePolicyIdentifier sigPolicyInfo
                                  )
        {
            String srcFileName = sourceFolder + "helloWorldDoc.pdf";

            X509Certificate[]  signChain      = Pkcs12FileHelper.ReadFirstChain(signCertFileName, password);
            ICipherParameters  signPrivateKey = Pkcs12FileHelper.ReadFirstKey(signCertFileName, password, password);
            IExternalSignature pks            = new PrivateKeySignature(signPrivateKey, DigestAlgorithms.SHA256);
            PdfSigner          signer         = new PdfSigner(new PdfReader(srcFileName), new FileStream(outFileName, FileMode.Create),
                                                              new StampingProperties());

            signer.SetFieldName("Signature1");
            signer.GetSignatureAppearance().SetPageRect(new Rectangle(50, 650, 200, 100)).SetReason("Test").SetLocation
                ("TestCity").SetLayer2Text("Approval test signature.\nCreated by iText7.");
            if (sigPolicyInfo == null)
            {
                signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
            }
            else
            {
                signer.SignDetached(pks, signChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES, sigPolicyInfo);
            }
        }