Example usage for org.bouncycastle.tsp TimeStampToken getTimeStampInfo

List of usage examples for org.bouncycastle.tsp TimeStampToken getTimeStampInfo

Introduction

In this page you can find the example usage for org.bouncycastle.tsp TimeStampToken getTimeStampInfo.

Prototype

public TimeStampTokenInfo getTimeStampInfo() 

Source Link

Usage

From source file:com.itextpdf.text.pdf.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 *///from   w  w  w .j  av  a2  s. c  o  m
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
    byte[] respBytes = null;
    try {
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), 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) {
            // @todo: Translate value of 15 error codes defined by 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()));
        }
        TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view 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);
    }
}

From source file:com.spilowagie.text.pdf.TSAClientBouncyCastle.java

License:Mozilla Public License

/**
 * Get timestamp token - Bouncy Castle request encoding / decoding layer
 */// w ww .jav  a2s . c om
protected byte[] getTimeStampToken(byte[] imprint) throws Exception {
    byte[] respBytes = null;
    try {
        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        // tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(X509ObjectIdentifiers.id_SHA1.getId(), 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) {
            // @todo: Translate value of 15 error codes defined by PKIFailureInfo to string
            throw new Exception("Invalid TSA '" + tsaURL + "' response, code " + 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(
                    "TSA '" + tsaURL + "' failed to return time stamp token: " + response.getStatusString());
        }
        TimeStampTokenInfo info = tsToken.getTimeStampInfo(); // to view 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("Failed to get TSA response from '" + tsaURL + "'", t);
    }
}

From source file:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java

License:Open Source License

/**
 * Se reimplementa este metodo para establecer un OID mediante el metodo
 * tsqGenerator.setReqPolicy()//www . jav a  2  s.  com
 */
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);

    // Se agrega una PID Policy:
    if (policy != null && policy.length() > 0) {
        tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy));
    }

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(
            new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(getDigestAlgorithm())), 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) {
        // @todo: Translate value of 15 error codes defined by
        // PKIFailureInfo to string
        throw new IOException(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 IOException(MessageLocalization.getComposedMessage(
                "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
    }
    tsToken.getTimeStampInfo(); // to view details
    byte[] encoded = tsToken.getEncoded();

    // Update our token size estimate for the next call (padded to be safe)
    this.tokenSizeEstimate = encoded.length + 32;
    return encoded;
}

From source file:ec.rubrica.pdf.tsa.TSAClientBouncyCastleWithOid.java

License:Open Source License

/**
 * Se reimplementa este metodo para establecer un OID mediante el metodo
 * tsqGenerator.setReqPolicy()//from   w  ww.  j a  va 2  s . co  m
 */
public byte[] getTimeStampToken54(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);

    // Se agrega una PID Policy:
    if (policy != null && policy.length() > 0) {
        tsqGenerator.setReqPolicy(new ASN1ObjectIdentifier(policy));
    }

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(
            new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(digestAlgorithm)), 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) {
        // @todo: Translate value of 15 error codes defined by
        // PKIFailureInfo to string
        throw new IOException(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 IOException(MessageLocalization.getComposedMessage(
                "tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
    }
    TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view
    // details
    byte[] encoded = tsToken.getEncoded();

    LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime());

    // QUITAR COMENTARIO:
    // if (tsaInfo != null) {
    // tsaInfo.inspectTimeStampTokenInfo(tsTokenInfo);
    // }
    // Update our token size estimate for the next call (padded to be safe)
    this.tokenSizeEstimate = encoded.length + 32;
    return encoded;
}

From source file:ee.ria.xroad.common.asic.AsicContainerVerifier.java

License:Open Source License

private Date verifyTimestamp() throws Exception {
    TimeStampToken tsToken = getTimeStampToken();

    TimestampVerifier.verify(tsToken, getTimestampedData(), GlobalConf.getTspCertificates());

    timestampDate = tsToken.getTimeStampInfo().getGenTime();
    timestampCert = TimestampVerifier.getSignerCertificate(tsToken, GlobalConf.getTspCertificates());

    return tsToken.getTimeStampInfo().getGenTime();
}

From source file:ee.ria.xroad.common.signature.TimestampVerifier.java

License:Open Source License

/**
 * Verifies that time-stamp applies to <code>stampedData</code>
 * and that it is signed by a trusted time-stamping authority
 * @param tsToken the time-stamp token//  w  w w.  j  a  v a 2 s . co m
 * @param stampedData the allegedly time-stamped data
 * @param tspCerts list of TSP certificates
 * @throws Exception if the verification failed
 */
public static void verify(TimeStampToken tsToken, byte[] stampedData, List<X509Certificate> tspCerts)
        throws Exception {
    String thatHash = encodeBase64(calculateDigest(tsToken.getTimeStampInfo().getHashAlgorithm(), stampedData));
    String thisHash = encodeBase64(tsToken.getTimeStampInfo().getMessageImprintDigest());
    if (!thisHash.equals(thatHash)) {
        throw new CodedException(X_MALFORMED_SIGNATURE, "Timestamp hashes do not match");
    }

    verify(tsToken, tspCerts);
}

From source file:es.mityc.firmaJava.ts.TSCliente.java

License:LGPL

/**
 * Este mtodo valida el Sello de Tiempo//from  w  ww .  j  a  v a  2 s.  com
 * @param binarioaSellar fichero binario a validar
 * @param sellodeTiempo El Sello de Tiempo se ingresa en formato binario
 * @return TSValidacion Valores TSA
 * @throws NoSuchAlgorithmException
 * @throws TSPException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws TSClienteError
 */
public static TSValidacion validarSelloTiempo(byte[] binarioaSellar, byte[] sellodeTiempo)
        throws NoSuchAlgorithmException, TSPException, IOException, NoSuchProviderException, CertStoreException,
        TSClienteError {

    //       Set permitidos = new HashSet(Arrays.asList(TSPAlgoritmos.getValoresPermitidos()));
    //       si el algoritmo pasado no es permitido o es nulo se usa el algortimo por defecto

    TimeStampToken tst = null;
    TSValidacion tsv = new TSValidacion();

    try {
        tst = new TimeStampToken(new CMSSignedData(sellodeTiempo));
    } catch (CMSException e) {
        // Intenta obtenerlo como una TimeStampResp
        try {
            TimeStampResponse tsr = new TimeStampResponse(sellodeTiempo);
            tst = tsr.getTimeStampToken();
            if (tst == null)
                throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        } catch (TSPException ex) {
            throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        } catch (IOException ex) {
            throw new TSClienteError(I18n.getResource(ConstantesTSA.LIBRERIA_TSA_ERROR_2));
        }
    }

    tsv.setTst(tst);
    TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo();

    MessageDigest resumen = TSPAlgoritmos.getDigest(tokenInfo.getMessageImprintAlgOID());
    if (resumen == null) {
        tsv.setRespuesta(false);
        return tsv;
    }

    resumen.update(binarioaSellar);
    if (MessageDigest.isEqual(resumen.digest(), tst.getTimeStampInfo().getMessageImprintDigest())) {
        //TimeStampTokenInfo tokenInfo = tst.getTimeStampInfo();                          
        SimpleDateFormat formato = new SimpleDateFormat(FORMATO_FECHA);
        tsv.setFecha(formato.format(tokenInfo.getGenTime()));
        tsv.setFechaDate(tokenInfo.getGenTime());

        GenTimeAccuracy precision = tokenInfo.getGenTimeAccuracy();
        tsv.setPrecision(precision);

        long accuLong = 0;
        if (precision != null) {
            accuLong = (precision.getMicros() * 1L) + (precision.getMillis() * 1000L)
                    + (precision.getSeconds() * 1000000L);
        }
        tsv.setPrecisionLong(accuLong);

        tsv.setSello(tokenInfo.getSerialNumber());
        tsv.setFirmaDigest(new String(Base64Coder.encode(tokenInfo.getMessageImprintDigest())));
        tsv.setRespuesta(true);
        tsv.setSelloAlg(tokenInfo.getMessageImprintAlgOID());
        tsv.setEmisor(tst.getSID().getIssuer());
    } else {
        tsv.setRespuesta(false);
    }
    return tsv;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESSignatureExtension.java

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {//  ww w  .j  av  a 2 s .  c o m

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + DSSUtils.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new DSSNullReturnedException(TimeStampToken.class);
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = (SignerInformation) cmsSignedDataTimeStampToken
                    .getSignerInfos().getSigners().iterator().next();
            AttributeTable unsignedAttributes = CAdESSignature.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the timestampToken
 *///  ww  w  .j av  a2 s  .c  o m
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {

    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (OID.id_aa_ets_archiveTimestampV2.equals(attrType)
                || OID.id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

From source file:eu.europa.esig.dss.cades.signature.CAdESSignatureExtension.java

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {/*from  w w  w .  ja  v  a 2 s  . c om*/

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + Hex.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new NullPointerException();
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = cmsSignedDataTimeStampToken.getSignerInfos()
                    .getSigners().iterator().next();
            AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}