Search in sources :

Example 1 with TimeStampTokenInfo

use of org.bouncycastle.tsp.TimeStampTokenInfo in project itext2 by albfernandez.

the class PdfPKCS7 method verifyTimestampImprint.

/**
 * Checks if the timestamp refers to this document.
 * @throws java.security.NoSuchAlgorithmException on error
 * @return true if it checks false otherwise
 * @since	2.1.6
 */
public boolean verifyTimestampImprint() throws NoSuchAlgorithmException {
    if (timeStampToken == null)
        return false;
    MessageImprint imprint = timeStampToken.getTimeStampInfo().toASN1Structure().getMessageImprint();
    TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
    String algOID = info.getMessageImprintAlgOID().getId();
    byte[] md = MessageDigest.getInstance(getStandardJavaName(getDigest(algOID))).digest(digest);
    byte[] imphashed = imprint.getHashedMessage();
    boolean res = Arrays.equals(md, imphashed);
    return res;
}
Also used : MessageImprint(org.bouncycastle.asn1.tsp.MessageImprint) TimeStampTokenInfo(org.bouncycastle.tsp.TimeStampTokenInfo) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1String(org.bouncycastle.asn1.ASN1String)

Example 2 with TimeStampTokenInfo

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

the class AddValidationInformation method doValidation.

/**
 * Fetches certificate information from the last signature of the document and appends a DSS
 * with the validation information to the document.
 *
 * @param filename in file to extract signature
 * @param output where to write the changed document
 * @throws IOException
 */
private void doValidation(String filename, OutputStream output) throws IOException {
    certInformationHelper = new CertInformationCollector();
    CertSignatureInformation certInfo = null;
    try {
        PDSignature signature = SigUtils.getLastRelevantSignature(document);
        if (signature != null) {
            certInfo = certInformationHelper.getLastCertInfo(signature, filename);
            signDate = signature.getSignDate();
            if ("ETSI.RFC3161".equals(signature.getSubFilter())) {
                byte[] contents = signature.getContents();
                TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents));
                TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo();
                signDate = Calendar.getInstance();
                signDate.setTime(timeStampInfo.getGenTime());
            }
        }
    } catch (TSPException | CMSException | CertificateProccessingException e) {
        throw new IOException("An Error occurred processing the Signature", e);
    }
    if (certInfo == null) {
        throw new IOException("No Certificate information or signature found in the given document");
    }
    PDDocumentCatalog docCatalog = document.getDocumentCatalog();
    COSDictionary catalog = docCatalog.getCOSObject();
    catalog.setNeedToBeUpdated(true);
    COSDictionary dss = getOrCreateDictionaryEntry(COSDictionary.class, catalog, "DSS");
    addExtensions(docCatalog);
    vriBase = getOrCreateDictionaryEntry(COSDictionary.class, dss, "VRI");
    ocsps = getOrCreateDictionaryEntry(COSArray.class, dss, "OCSPs");
    crls = getOrCreateDictionaryEntry(COSArray.class, dss, "CRLs");
    certs = getOrCreateDictionaryEntry(COSArray.class, dss, "Certs");
    addRevocationData(certInfo);
    addAllCertsToCertArray();
    // write incremental
    document.saveIncremental(output);
}
Also used : COSDictionary(org.apache.pdfbox.cos.COSDictionary) CertSignatureInformation(org.apache.pdfbox.examples.signature.validation.CertInformationCollector.CertSignatureInformation) IOException(java.io.IOException) PDSignature(org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature) CMSSignedData(org.bouncycastle.cms.CMSSignedData) PDDocumentCatalog(org.apache.pdfbox.pdmodel.PDDocumentCatalog) COSArray(org.apache.pdfbox.cos.COSArray) TimeStampTokenInfo(org.bouncycastle.tsp.TimeStampTokenInfo) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) CMSException(org.bouncycastle.cms.CMSException)

Example 3 with TimeStampTokenInfo

use of org.bouncycastle.tsp.TimeStampTokenInfo in project OpenPDF by LibrePDF.

the class TSAClientBouncyCastle method getTimeStampToken.

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 * @param imprint a byte array containing the imprint
 * @return the timestamp token
 * @throws Exception on error
 */
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
    byte[] respBytes = null;
    try {
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (isNotEmpty(policy)) {
            tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy));
        }
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        ASN1ObjectIdentifier digestOid = X509ObjectIdentifiers.id_SHA1;
        if (isNotEmpty(digestName)) {
            digestOid = new ASN1ObjectIdentifier(PdfPKCS7.getDigestOid(digestName));
        }
        TimeStampRequest request = tsqGenerator.generate(digestOid, imprint, nonce);
        byte[] requestBytes = request.getEncoded();
        // Call the communications layer
        respBytes = getTSAResponse(requestBytes);
        // Handle the TSA response
        TimeStampResponse response = new TimeStampResponse(respBytes);
        // validate communication level attributes (RFC 3161 PKIStatus)
        response.validate(request);
        PKIFailureInfo failure = response.getFailInfo();
        int value = (failure == null) ? 0 : failure.intValue();
        if (value != 0) {
            // PKIFailureInfo to string
            throw new Exception(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL, String.valueOf(value)));
        }
        // @todo: validate the time stap certificate chain (if we want
        // assure we do not sign using an invalid timestamp).
        // extract just the time stamp token (removes communication status
        // info)
        TimeStampToken tsToken = response.getTimeStampToken();
        if (tsToken == null) {
            throw new Exception(MessageLocalization.getComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
        }
        // to view
        TimeStampTokenInfo info = tsToken.getTimeStampInfo();
        // details
        byte[] encoded = tsToken.getEncoded();
        long stop = System.currentTimeMillis();
        // Update our token size estimate for the next call (padded to be
        // safe)
        this.tokSzEstimate = encoded.length + 32;
        return encoded;
    } catch (Exception e) {
        throw e;
    } catch (Throwable t) {
        throw new Exception(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL), t);
    }
}
Also used : TimeStampRequest(org.bouncycastle.tsp.TimeStampRequest) GeneralSecurityException(java.security.GeneralSecurityException) PKIFailureInfo(org.bouncycastle.asn1.cmp.PKIFailureInfo) TimeStampResponse(org.bouncycastle.tsp.TimeStampResponse) BigInteger(java.math.BigInteger) TimeStampRequestGenerator(org.bouncycastle.tsp.TimeStampRequestGenerator) TimeStampTokenInfo(org.bouncycastle.tsp.TimeStampTokenInfo) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with TimeStampTokenInfo

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

the class TimeStampOperator method validate.

/**
 * Validate a time stamp
 *
 * @param content   if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash      if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();
        int verified = 0;
        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
            if (signer.verify(siv)) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
            timeStampToken.validate(siv);
        }
        logger.debug(timeStampMessagesBundle.getString("info.signature.verified", verified));
        // Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID();
            digest.setAlgorithm(algOID.toString());
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }
        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.debug(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            logger.error(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }
    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        logger.error(ex.getMessage());
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TimeStampTokenInfo(org.bouncycastle.tsp.TimeStampTokenInfo) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 5 with TimeStampTokenInfo

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

the class ShowSignature method verifyETSIdotRFC3161.

/**
 * Verify ETSI.RFC3161 TimeStampToken
 *
 * @param signedContentAsStream the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @throws CMSException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws TSPException
 * @throws OperatorCreationException
 * @throws CertificateVerificationException
 * @throws CertificateException
 */
private void verifyETSIdotRFC3161(InputStream signedContentAsStream, byte[] contents) throws CMSException, NoSuchAlgorithmException, IOException, TSPException, OperatorCreationException, CertificateVerificationException, CertificateException {
    TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(contents));
    TimeStampTokenInfo timeStampInfo = timeStampToken.getTimeStampInfo();
    System.out.println("Time stamp gen time: " + timeStampInfo.getGenTime());
    if (timeStampInfo.getTsa() != null) {
        System.out.println("Time stamp tsa name: " + timeStampInfo.getTsa().getName());
    }
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream certStream = new ByteArrayInputStream(contents);
    Collection<? extends Certificate> certs = factory.generateCertificates(certStream);
    System.out.println("certs=" + certs);
    String hashAlgorithm = timeStampInfo.getMessageImprintAlgOID().getId();
    // compare the hash of the signed content with the hash in the timestamp
    MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
    try (DigestInputStream dis = new DigestInputStream(signedContentAsStream, md)) {
        while (dis.read() != -1) {
        // do nothing
        }
    }
    if (Arrays.equals(md.digest(), timeStampInfo.getMessageImprintDigest())) {
        System.out.println("ETSI.RFC3161 timestamp signature verified");
    } else {
        System.err.println("ETSI.RFC3161 timestamp signature verification failed");
    }
    X509Certificate certFromTimeStamp = (X509Certificate) certs.iterator().next();
    SigUtils.checkTimeStampCertificateUsage(certFromTimeStamp);
    SigUtils.validateTimestampToken(timeStampToken);
    SigUtils.verifyCertificateChain(timeStampToken.getCertificates(), certFromTimeStamp, timeStampInfo.getGenTime());
}
Also used : DigestInputStream(java.security.DigestInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TimeStampTokenInfo(org.bouncycastle.tsp.TimeStampTokenInfo) COSString(org.apache.pdfbox.cos.COSString) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) MessageDigest(java.security.MessageDigest) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Aggregations

TimeStampTokenInfo (org.bouncycastle.tsp.TimeStampTokenInfo)9 TimeStampToken (org.bouncycastle.tsp.TimeStampToken)7 CMSSignedData (org.bouncycastle.cms.CMSSignedData)5 IOException (java.io.IOException)3 PDSignature (org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature)3 CMSException (org.bouncycastle.cms.CMSException)3 TSPException (org.bouncycastle.tsp.TSPException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 X509Certificate (java.security.cert.X509Certificate)2 COSArray (org.apache.pdfbox.cos.COSArray)2 COSDictionary (org.apache.pdfbox.cos.COSDictionary)2 CertSignatureInformation (org.apache.pdfbox.examples.signature.validation.CertInformationCollector.CertSignatureInformation)2 PDDocumentCatalog (org.apache.pdfbox.pdmodel.PDDocumentCatalog)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)2 ASN1String (org.bouncycastle.asn1.ASN1String)2 DEROctetString (org.bouncycastle.asn1.DEROctetString)2 MessageImprint (org.bouncycastle.asn1.tsp.MessageImprint)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 SignerInformation (org.bouncycastle.cms.SignerInformation)2