Search in sources :

Example 1 with TimeStampToken

use of org.bouncycastle.tsp.TimeStampToken in project tika by apache.

the class TSDParser method extractMetas.

private List<TSDMetas> extractMetas(InputStream stream) {
    List<TSDMetas> tsdMetasList = new ArrayList<>();
    try {
        CMSTimeStampedData cmsTimeStampedData = new CMSTimeStampedData(stream);
        TimeStampToken[] tokens = cmsTimeStampedData.getTimeStampTokens();
        for (int i = 0; i < tokens.length; i++) {
            TSDMetas tsdMetas = new TSDMetas(true, tokens[i].getTimeStampInfo().getGenTime(), tokens[i].getTimeStampInfo().getPolicy().getId(), tokens[i].getTimeStampInfo().getSerialNumber(), tokens[i].getTimeStampInfo().getTsa(), tokens[i].getTimeStampInfo().getHashAlgorithm().getAlgorithm().getId());
            tsdMetasList.add(tsdMetas);
        }
    } catch (Exception ex) {
        LOG.error("Error in TSDParser.buildMetas {}", ex.getMessage());
        tsdMetasList.clear();
    }
    return tsdMetasList;
}
Also used : CMSTimeStampedData(org.bouncycastle.tsp.cms.CMSTimeStampedData) ArrayList(java.util.ArrayList) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) TikaException(org.apache.tika.exception.TikaException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAXException(org.xml.sax.SAXException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with TimeStampToken

use of org.bouncycastle.tsp.TimeStampToken in project pdfbox by apache.

the class ShowSignature method showSignature.

private void showSignature(String[] args) throws IOException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, TSPException {
    if (args.length != 2) {
        usage();
    } else {
        String password = args[0];
        File infile = new File(args[1]);
        try (PDDocument document = PDDocument.load(infile, password)) {
            for (PDSignature sig : document.getSignatureDictionaries()) {
                COSDictionary sigDict = sig.getCOSObject();
                COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
                // download the signed content
                byte[] buf;
                try (FileInputStream fis = new FileInputStream(infile)) {
                    buf = sig.getSignedContent(fis);
                }
                System.out.println("Signature found");
                int[] byteRange = sig.getByteRange();
                if (byteRange.length != 4) {
                    System.err.println("Signature byteRange must have 4 items");
                } else {
                    long fileLen = infile.length();
                    long rangeMax = byteRange[2] + (long) byteRange[3];
                    // multiply content length with 2 (because it is in hex in the PDF) and add 2 for < and >
                    int contentLen = contents.getString().length() * 2 + 2;
                    if (fileLen != rangeMax || byteRange[0] != 0 || byteRange[1] + contentLen != byteRange[2]) {
                        // a false result doesn't necessarily mean that the PDF is a fake
                        // see this answer why:
                        // https://stackoverflow.com/a/48185913/535646
                        System.out.println("Signature does not cover whole document");
                    } else {
                        System.out.println("Signature covers whole document");
                    }
                }
                if (sig.getName() != null) {
                    System.out.println("Name:     " + sig.getName());
                }
                if (sig.getSignDate() != null) {
                    System.out.println("Modified: " + sdf.format(sig.getSignDate().getTime()));
                }
                String subFilter = sig.getSubFilter();
                if (subFilter != null) {
                    switch(subFilter) {
                        case "adbe.pkcs7.detached":
                        case "ETSI.CAdES.detached":
                            verifyPKCS7(buf, contents, sig);
                            // TODO check certificate chain, revocation lists, timestamp...
                            break;
                        case "adbe.pkcs7.sha1":
                            {
                                // example: PDFBOX-1452.pdf
                                byte[] certData = contents.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                                byte[] hash = MessageDigest.getInstance("SHA1").digest(buf);
                                verifyPKCS7(hash, contents, sig);
                                // TODO check certificate chain, revocation lists, timestamp...
                                break;
                            }
                        case "adbe.x509.rsa_sha1":
                            {
                                // example: PDFBOX-2693.pdf
                                COSString certString = (COSString) sigDict.getDictionaryObject(COSName.CERT);
                                if (certString == null) {
                                    System.err.println("The /Cert certificate string is missing in the signature dictionary");
                                    return;
                                }
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                                // TODO verify signature
                                break;
                            }
                        case "ETSI.RFC3161":
                            TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents.getBytes()));
                            System.out.println("Time stamp gen time: " + timeStampToken.getTimeStampInfo().getGenTime());
                            System.out.println("Time stamp tsa name: " + timeStampToken.getTimeStampInfo().getTsa().getName());
                            CertificateFactory factory = CertificateFactory.getInstance("X.509");
                            ByteArrayInputStream certStream = new ByteArrayInputStream(contents.getBytes());
                            Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
                            System.out.println("certs=" + certs);
                            // TODO verify signature
                            break;
                        default:
                            System.err.println("Unknown certificate type: " + subFilter);
                            break;
                    }
                } else {
                    throw new IOException("Missing subfilter for cert dictionary");
                }
            }
            analyseDSS(document);
        } catch (CMSException | OperatorCreationException ex) {
            throw new IOException(ex);
        }
        System.out.println("Analyzed: " + args[1]);
    }
}
Also used : COSDictionary(org.apache.pdfbox.cos.COSDictionary) COSString(org.apache.pdfbox.cos.COSString) IOException(java.io.IOException) PDSignature(org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature) CertificateFactory(java.security.cert.CertificateFactory) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) Collection(java.util.Collection) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File) COSString(org.apache.pdfbox.cos.COSString) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CMSException(org.bouncycastle.cms.CMSException)

Example 3 with TimeStampToken

use of org.bouncycastle.tsp.TimeStampToken in project pdfbox by apache.

the class TSAClient method getTimeStampToken.

/**
 * @param messageImprint imprint of message contents
 * @return the encoded time stamp token
 * @throws IOException if there was an error with the connection or data from the TSA server,
 *                     or if the time stamp response could not be validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);
    // 32-bit cryptographic nonce
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();
    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());
    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }
    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }
    return token.getEncoded();
}
Also used : TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) SecureRandom(java.security.SecureRandom) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest)

Example 4 with TimeStampToken

use of org.bouncycastle.tsp.TimeStampToken in project xades4j by luisgoncalves.

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Example 5 with TimeStampToken

use of org.bouncycastle.tsp.TimeStampToken in project signer by demoiselle.

the class CAdESChecker method validateTimestamp.

/**
 *  validade a timestampo on signature
 * @param attributeTimeStamp
 * @param varSignature
 * @return
 */
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) {
    try {
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
        Timestamp timeStampSigner = new Timestamp(timeStampToken);
        timeStampOperator.validate(varSignature, varTimeStamp, null);
        return timeStampSigner;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}
Also used : TimeStampOperator(org.demoiselle.signer.timestamp.connector.TimeStampOperator) IOException(java.io.IOException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Timestamp(org.demoiselle.signer.timestamp.Timestamp) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

IOException (java.io.IOException)11 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)11 TSPException (org.bouncycastle.tsp.TSPException)8 CMSException (org.bouncycastle.cms.CMSException)5 CMSSignedData (org.bouncycastle.cms.CMSSignedData)5 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)4 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)4 TimeStampResponse (org.bouncycastle.tsp.TimeStampResponse)4 CertificateCoreException (org.demoiselle.signer.core.exception.CertificateCoreException)4 BigInteger (java.math.BigInteger)3 MessageDigest (java.security.MessageDigest)3 X509Certificate (java.security.cert.X509Certificate)3 TimeStampRequest (org.bouncycastle.tsp.TimeStampRequest)3 TimeStampRequestGenerator (org.bouncycastle.tsp.TimeStampRequestGenerator)3 Timestamp (org.demoiselle.signer.timestamp.Timestamp)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SecureRandom (java.security.SecureRandom)2 CertificateException (java.security.cert.CertificateException)2 ArrayList (java.util.ArrayList)2 PKIFailureInfo (org.bouncycastle.asn1.cmp.PKIFailureInfo)2