Example usage for org.bouncycastle.tsp TimeStampTokenInfo getGenTime

List of usage examples for org.bouncycastle.tsp TimeStampTokenInfo getGenTime

Introduction

In this page you can find the example usage for org.bouncycastle.tsp TimeStampTokenInfo getGenTime.

Prototype

public Date getGenTime() 

Source Link

Usage

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

License:Open Source License

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/* w  ww. j  ava  2s .co m*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

From source file:com.itextpdf.signatures.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get RFC 3161 timeStampToken.//from  w  w  w.j  av  a2s  .c o m
 * Method may return null indicating that timestamp should be skipped.
 * @param imprint data imprint to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 * @throws TSPException
 */
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // 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(SystemUtil.getSystemTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(
            new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigest(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 PdfException(PdfException.InvalidTsa1ResponseCode2).setMessageParams(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 PdfException(PdfException.Tsa1FailedToReturnTimeStampToken2).setMessageParams(tsaURL,
                response.getStatusString());
    }
    TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view details
    byte[] encoded = tsToken.getEncoded();

    LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime());
    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:com.itextpdf.text.pdf.security.TSAClientBouncyCastle.java

License:Open Source License

/**
 * Get RFC 3161 timeStampToken./*from w ww.j a v a  2s.c om*/
 * Method may return null indicating that timestamp should be skipped.
 * @param imprint data imprint to be time-stamped
 * @return encoded, TSA signed data of the timeStampToken
 * @throws IOException
 * @throws TSPException 
 */
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
    byte[] respBytes = null;
    // 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(
            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());
    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: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  w w.j  a v  a 2 s. c  o  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:es.mityc.firmaJava.ts.TSCliente.java

License:LGPL

/**
 * Este mtodo valida el Sello de Tiempo//from  w w  w  .  ja  v  a  2s. 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:org.linagora.linshare.core.service.impl.TimeStampingServiceImpl.java

License:Open Source License

public Date getGenerationTime(TimeStampResponse response) {
    TimeStampToken tsToken = response.getTimeStampToken();
    TimeStampTokenInfo tsInfo = tsToken.getTimeStampInfo();

    return tsInfo.getGenTime();
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

License:Open Source License

private void tsaPrintReply() throws Exception {
    final byte[] bytes = readFiletoBuffer(inrepstring);

    TimeStampResponse response = null;//from w  w w  .  java  2 s. c  o m
    out.println("Time-stamp response {");
    try {
        response = new TimeStampResponse(bytes);
        out.println("  Status:                           " + response.getStatus());
        out.println("  Status message:                   " + response.getStatusString());
    } catch (TSPException ex) {
        out.println("  Not a response");
    }
    if (response != null) {
        PKIFailureInfo failureInfo = response.getFailInfo();
        if (failureInfo != null) {
            out.print("  Failure info:                          ");
            out.println(failureInfo.intValue());
        }
    }

    final TimeStampToken token;
    if (response == null) {
        token = new TimeStampToken(new CMSSignedData(bytes));
    } else {
        token = response.getTimeStampToken();
    }
    if (token != null) {
        out.println("  Time-stamp token:");
        TimeStampTokenInfo info = token.getTimeStampInfo();
        if (info != null) {
            out.println("      Info:");
            out.print("         " + "Accuracy:                  ");
            out.println(info.getAccuracy() != null ? info.getAccuracy() : "(null)");

            out.print("         " + "Gen Time:                  ");
            out.println(info.getGenTime());

            out.print("         " + "Gen Time Accuracy:         ");
            out.println(info.getGenTimeAccuracy());

            out.print("         " + "Message imprint digest:    ");
            out.println(new String(Hex.encode(info.getMessageImprintDigest())));

            out.print("         " + "Message imprint algorithm: ");
            out.println(info.getMessageImprintAlgOID());

            out.print("         " + "Nonce:                     ");
            out.println(info.getNonce() != null ? info.getNonce().toString(16) : "(null)");

            out.print("         " + "Serial Number:             ");
            out.println(info.getSerialNumber() != null ? info.getSerialNumber().toString(16) : "(null)");

            out.print("         " + "TSA:                       ");
            out.println(info.getTsa() != null ? info.getTsa() : "(null)");

            out.print("         " + "Policy:                    ");
            out.println(info.getPolicy());
        }
        out.println("      Signer ID: ");
        out.println("         Serial Number:             " + token.getSID().getSerialNumber().toString(16));
        out.println("         Issuer:                    " + token.getSID().getIssuer());

        out.println("      Signer certificate:           ");

        Store certs = token.getCertificates();
        Selector signerSelector = new AttributeCertificateHolder(token.getSID().getIssuer(),
                token.getSID().getSerialNumber());

        Collection certCollection = certs.getMatches(signerSelector);
        for (Object o : certCollection) {
            if (o instanceof X509CertificateHolder) {
                X509CertificateHolder cert = (X509CertificateHolder) o;
                out.println("         Certificate: ");
                out.println("            Serial Number:          " + cert.getSerialNumber().toString(16));
                out.println("            Subject:                " + cert.getSubject());
                out.println("            Issuer:                 " + cert.getIssuer());
            } else {
                out.println("Not an X.509 certificate: " + o);
            }
        }

        out.println("      Other certificates: ");
        certCollection = certs.getMatches(new InvertedSelector(signerSelector));
        for (Object o : certCollection) {
            if (o instanceof X509CertificateHolder) {
                X509CertificateHolder cert = (X509CertificateHolder) o;
                out.println("         Certificate: ");
                out.println("            Serial Number:          " + cert.getSerialNumber().toString(16));
                out.println("            Subject:                " + cert.getSubject());
                out.println("            Issuer:                 " + cert.getIssuer());
            } else {
                out.println("Not an X.509 certificate: " + o);
            }
        }
    }
    out.println("}");
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

License:Open Source License

private void tsaVerify() throws Exception {
    if (inrepstring == null) {
        LOG.error("Needs an inrep!");
    } else if (signerfilestring == null) {
        LOG.error("Needs a signerfile!");
    } else {// w  ww.  java 2 s  .c om
        final Collection<X509Certificate> col = getCertsFromPEM(signerfilestring);
        final X509Certificate[] list = (X509Certificate[]) col.toArray(new X509Certificate[0]);
        if (list.length == 0) {
            LOG.error("No certificate found in file: " + signerfilestring);
            return;
        }

        final byte[] b64Bytes = readFiletoBuffer(inrepstring);
        final byte[] replyBytes = Base64.decode(b64Bytes);

        final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
        final TimeStampToken token = timeStampResponse.getTimeStampToken();
        final SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider("BC").build(list[0]);
        token.validate(infoVerifier);
        LOG.info("Token was validated successfully.");

        final TimeStampTokenInfo info = token.getTimeStampInfo();
        LOG.info("Token was generated on: " + info.getGenTime());

        if (LOG.isDebugEnabled()) {
            if (info.getMessageImprintAlgOID().equals(TSPAlgorithms.SHA1)) {
                LOG.debug("Token hash alg: SHA1");
            } else {
                LOG.debug("Token hash alg: " + info.getMessageImprintAlgOID());
            }
        }
        final byte[] hexDigest = Hex.encode(info.getMessageImprintDigest());
        LOG.info("MessageDigest=" + new String(hexDigest));
    }
}

From source file:xades4j.providers.impl.DefaultTimeStampVerificationProvider.java

License:Open Source License

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput)
        throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;//  www  . j  ava2  s  .c  o  m
    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();
}