Package com.itextpdf.text.pdf.security

Examples of com.itextpdf.text.pdf.security.PdfPKCS7


            Map<String, PdfPKCS7> result = SignatureFinder.find(
                inputDocumentFileName, includeTimestamps);

            // Print signature name, signature date and certificate name for each signature.
            for (String signature : result.keySet()) {
                PdfPKCS7 pkcs7 = result.get(signature);
                Calendar signDate = pkcs7.getSignDate();
                String certificateName = CertificateValidator.getCertificateName(
                    pkcs7.getSigningCertificate());
                System.out.print(signature + ", ");
                System.out.print(DatatypeConverter.printDateTime(signDate) + ", ");
                System.out.println(certificateName);
            }
        } catch (Exception exception) {
View Full Code Here


            Map<String, PdfPKCS7> result = SignatureValidator.validateDocument(
                inputDocumentFileName, rootCertificatesFileName);

            // Print signature name, signature date and certificate name for each signature.
            for (String signature : result.keySet()) {
                PdfPKCS7 pkcs7 = result.get(signature);
                Calendar date = pkcs7.getSignDate();
                String signer = CertificateValidator.getCertificateName(
                    pkcs7.getSigningCertificate());
                System.out.print(signature + ", ");
                System.out.print(DatatypeConverter.printDateTime(date) + ", ");
                System.out.println(signer);
            }
        } catch (Exception exception) {
View Full Code Here

        Map<String, PdfPKCS7> result = new LinkedHashMap<String, PdfPKCS7>();

        // Get signature data encoded in PKCS #7 format for each signature.
        for (String signature : signatures) {
            // Verify the signature.
            PdfPKCS7 pkcs7 = fields.verifySignature(signature);

            // Check if the signature is a document level timestamp.
            if (pkcs7.isTsp() && !includeTimestamps) {
                // Skip document level timestamps.
                continue;
            }

            // Store the signature data.
View Full Code Here

                "Document_has_no_signature."));
        }

        // Check if the last signature is a timestamp.
        String lastSignature = signatures.get(signatures.size() - 1);
        PdfPKCS7 pkcs7 = fields.verifySignature(lastSignature);
        if (pkcs7.isTsp()) {
            // Prepare to store certificates, OCSP responses and CRLs only for the last timestamp.
            signatures.clear();
            signatures.add(lastSignature);
        }

        // Prepare structures to store all certificates and CRLs.
        ArrayList<X509Certificate> allCertificates = new ArrayList<X509Certificate>();
        ArrayList<String> allCRLDistributionPoints = new ArrayList<String>();
        HashMap<String, ArrayList<X509Certificate>> certMap = new HashMap<String, ArrayList<X509Certificate>>();
        HashMap<String, ArrayList<X509CRL>> crlMap = new HashMap<String, ArrayList<X509CRL>>();
        HashMap<String, ArrayList<BasicOCSPResp>> ocspMap = new HashMap<String, ArrayList<BasicOCSPResp>>();

        // Store certificates, OCSP responses and CRLs for each signature.
        for (String signature : signatures) {
            // Get signature data.
            pkcs7 = fields.verifySignature(signature);

            // Get certificate path.
            X509Certificate signingCertificate = (X509Certificate) factory.generateCertificate(
                new ByteArrayInputStream(pkcs7.getSigningCertificate().getEncoded()));
            Certificate[] chain = pkcs7.getSignCertificateChain();
            ArrayList<X509Certificate> intermediateCertificates = new ArrayList<X509Certificate>();
            for (Certificate intermediateCertificate : chain) {
                intermediateCertificates.add((X509Certificate) factory.generateCertificate(
                    new ByteArrayInputStream(intermediateCertificate.getEncoded())));
            }
View Full Code Here

        NoCRLException,
        GeneralSecurityException
    {
        // Get all the information about the signature.
        AcroFields fields = reader.getAcroFields();
        PdfPKCS7 pkcs7 = fields.verifySignature(signature);

        // Use the signature to check the document integrity.
        if (!pkcs7.verify()) {
            throw new InvalidSignatureException(
                String.format(messages.getString(
                "Document_was_modified_or_corrupted_after_the_signature__%s"),
                signature));
        }

        // Get the signing certificate.
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) factory.generateCertificate(
            new ByteArrayInputStream(pkcs7.getSigningCertificate().getEncoded()));

        // Get the certificate chain.
        Certificate[] chain = pkcs7.getSignCertificateChain();
        ArrayList<X509Certificate> intermediateCertificates = new ArrayList<X509Certificate>();
        for (Certificate intermediateCertificate : chain) {
            intermediateCertificates.add((X509Certificate) factory.generateCertificate(
                new ByteArrayInputStream(intermediateCertificate.getEncoded())));
        }

        // Validate the certificate on date of signature.
        certificate.checkValidity(pkcs7.getSignDate().getTime());

        // Validate the certificate on the specified date.
        CertificateValidator.validate(
            certificate,
            intermediateCertificates,
View Full Code Here

                "Document_has_no_signature."));
        }

        // Check if the last signature is a timestamp.
        String lastSignature = signatures.get(signatures.size() - 1);
        PdfPKCS7 pkcs7 = fields.verifySignature(lastSignature);
        if (!pkcs7.isTsp()) {
            throw new NoTimestampException(messages.getString(
                "Document_has_no_document_level_timestamp."));
        }

        // Get the expiration date of the last timestamp.
        Calendar expiration = Calendar.getInstance();
        expiration.setTime(pkcs7.getSigningCertificate().getNotAfter());

        // Validate last timestamp on the current date.
        SignatureValidator.validate(lastSignature, reader, rootCertificates);

        // Get OCSP responses and CRLs from DSS to validate old signatures.
        PdfDictionary dictionary = reader.getCatalog().getAsDict(PdfName.DSS);
        if (dictionary == null) {
            throw new NoDSSException(messages.getString(
                "Document_has_no_DSS_(Document_Security_Store)."));
        }
        PdfArray ocspArray = dictionary.getAsArray(PdfName.OCSPS);
        ArrayList<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
        if (ocspArray != null) {
            for (int i = 0; i < ocspArray.size(); i++) {
                PRStream stream = (PRStream) ocspArray.getAsStream(i);
                OCSPResp response = new OCSPResp(PdfReader.getStreamBytes(stream));
                BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject();
                ocsps.add(basicResponse);
            }
        }
        PdfArray crlArray = dictionary.getAsArray(PdfName.CRLS);
        ArrayList<X509CRL> crls = new ArrayList<X509CRL>();
        if (crlArray != null) {
            for (int i = 0; i < crlArray.size(); i++) {
                PRStream stream = (PRStream) crlArray.getAsStream(i);
                X509CRL crl = (X509CRL) factory.generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes(stream)));
                crls.add(crl);
            }
        }
        if (ocsps.size() == 0 && crls.size() == 0) {
            throw new NoRevocationStatusException(messages.getString(
                "Document_has_neither_OCSP_responses_nor_CRLs_for_offline_check_of_certificate_revocation_status."));
        }

        // Use date from last timestamp to validade next signature.
        Calendar date = pkcs7.getTimeStampDate();

        // Validate others signatures using date of the timestamp.
        for (int i = signatures.size() - 2; i >= 0; i--) {
            // Get next signature.
            pkcs7 = fields.verifySignature(signatures.get(i));

            // Validate next signature.
            SignatureValidator.validate(
                signatures.get(i), reader, rootCertificates, ocsps, crls, date);

            // Use date from current timestamp to validade next signatures.
            if (pkcs7.isTsp()) {
                date = pkcs7.getTimeStampDate();
            }
        }

        // Return the expiration date of the last timestamp.
        return expiration;
View Full Code Here

        if (v == null)
            return null;
        try {
            PdfName sub = v.getAsName(PdfName.SUBFILTER);
            PdfString contents = v.getAsString(PdfName.CONTENTS);
            PdfPKCS7 pk = null;
            if (sub.equals(PdfName.ADBE_X509_RSA_SHA1)) {
                PdfString cert = v.getAsString(PdfName.CERT);
                if (cert == null)
                    cert = v.getAsArray(PdfName.CERT).getAsString(0);
                pk = new PdfPKCS7(contents.getOriginalBytes(), cert.getBytes(), provider);
            }
            else
                pk = new PdfPKCS7(contents.getOriginalBytes(), sub, provider);
            updateByteRange(pk, v);
            PdfString str = v.getAsString(PdfName.M);
            if (str != null)
                pk.setSignDate(PdfDate.decode(str.toString()));
            PdfObject obj = PdfReader.getPdfObject(v.get(PdfName.NAME));
            if (obj != null) {
              if (obj.isString())
                pk.setSignName(((PdfString)obj).toUnicodeString());
              else if(obj.isName())
                pk.setSignName(PdfName.decodeName(obj.toString()));
            }
            str = v.getAsString(PdfName.REASON);
            if (str != null)
                pk.setReason(str.toUnicodeString());
            str = v.getAsString(PdfName.LOCATION);
            if (str != null)
                pk.setLocation(str.toUnicodeString());
            return pk;
        }
        catch (Exception e) {
            throw new ExceptionConverter(e);
        }
View Full Code Here

        if (v == null)
            return null;
        try {
            PdfName sub = v.getAsName(PdfName.SUBFILTER);
            PdfString contents = v.getAsString(PdfName.CONTENTS);
            PdfPKCS7 pk = null;
            if (sub.equals(PdfName.ADBE_X509_RSA_SHA1)) {
                PdfString cert = v.getAsString(PdfName.CERT);
                if (cert == null)
                    cert = v.getAsArray(PdfName.CERT).getAsString(0);
                pk = new PdfPKCS7(contents.getOriginalBytes(), cert.getBytes(), provider);
            }
            else
                pk = new PdfPKCS7(contents.getOriginalBytes(), sub, provider);
            updateByteRange(pk, v);
            PdfString str = v.getAsString(PdfName.M);
            if (str != null)
                pk.setSignDate(PdfDate.decode(str.toString()));
            PdfObject obj = PdfReader.getPdfObject(v.get(PdfName.NAME));
            if (obj != null) {
              if (obj.isString())
                pk.setSignName(((PdfString)obj).toUnicodeString());
              else if(obj.isName())
                pk.setSignName(PdfName.decodeName(obj.toString()));
            }
            str = v.getAsString(PdfName.REASON);
            if (str != null)
                pk.setReason(str.toUnicodeString());
            str = v.getAsString(PdfName.LOCATION);
            if (str != null)
                pk.setLocation(str.toUnicodeString());
            return pk;
        }
        catch (Exception e) {
            throw new ExceptionConverter(e);
        }
View Full Code Here

      Collection<Signature> signatures = new ArrayList<Signature>();
      if (fields != null) {
        List<String> list = fields.getSignatureNames();
        if ((list != null) && (!list.isEmpty())) {
          for (String str : list) {
            PdfPKCS7 pk = fields.verifySignature(str);

            PdfString string = fields.getSignatureDictionary(str).getAsString(PdfName.CONTENTS);
            byte[] content = string.getBytes();

            X509Certificate certificate = pk.getSigningCertificate();

            byte[] encoded = content;
            TimeStamp timeStamp = null;
            String location = pk.getLocation();
            String reason = pk.getReason();
            String signName = pk.getSignName();
            Date date = pk.getSignDate().getTime();
            Boolean valid = Boolean.TRUE;
            Signatory signatory = this.toSignatory(certificate);

            Store store = new JCAStore(KeyStoreType.JKS);
            store.add(new CertificateEntry(new Alias(certificate.getSerialNumber().toString()), certificate));

            if (pk.verify()) {
              valid = Boolean.FALSE;
            }

            Object[] fails = CertificateVerification.verifyCertificates(pk.getCertificates(), keystore, null, pk.getSignDate());
            if (Conditions.isNotEmpty(fails)) {
              valid = Boolean.FALSE;
            }

            TimeStampToken timeStampToken = pk.getTimeStampToken();
            if (timeStampToken != null) {
              timeStamp = BouncyCastleTimeStampHelper.toTimeStamp(timeStampToken);
              timeStampToken.getTimeStampInfo();
              if (valid.booleanValue()) {
                boolean ok = pk.verifyTimestampImprint();
                valid = Boolean.valueOf(ok);
              }
            }

            Signature sig = new Signature();
View Full Code Here

      Collection<Signature> signatures = new ArrayList<Signature>();
      if (fields != null) {
        List<String> list = fields.getSignatureNames();
        if ((list != null) && (!list.isEmpty())) {
          for (String str : list) {
            PdfPKCS7 pk = fields.verifySignature(str);

            PdfString string = fields.getSignatureDictionary(str).getAsString(PdfName.CONTENTS);
            byte[] content = string.getBytes();

            X509Certificate certificate = pk.getSigningCertificate();

            byte[] encoded = content;
            TimeStamp timeStamp = null;
            String location = pk.getLocation();
            String reason = pk.getReason();
            String signName = pk.getSignName();
            Date date = pk.getSignDate().getTime();
            Boolean valid = Boolean.TRUE;
            Signatory signatory = this.toSignatory(certificate);

            Store store = new JCAStore(KeyStoreType.JKS);
            store.add(new CertificateEntry(new Alias(certificate.getSerialNumber().toString()), certificate));

            if (pk.verify()) {
              valid = Boolean.FALSE;
            }

            Object[] fails = CertificateVerification.verifyCertificates(pk.getCertificates(), keystore, null, pk.getSignDate());
            if (ConditionUtils.isNotEmpty(fails)) {
              valid = Boolean.FALSE;
            }

            TimeStampToken timeStampToken = pk.getTimeStampToken();
            if (timeStampToken != null) {
              timeStamp = BouncyCastleTimeStampHelper.toTimeStamp(timeStampToken);
              timeStampToken.getTimeStampInfo();
              if (valid.booleanValue()) {
                boolean ok = pk.verifyTimestampImprint();
                valid = Boolean.valueOf(ok);
              }
            }

            Signature sig = new Signature();
View Full Code Here

TOP

Related Classes of com.itextpdf.text.pdf.security.PdfPKCS7

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.