Example usage for org.bouncycastle.tsp TimeStampRequestGenerator setReqPolicy

List of usage examples for org.bouncycastle.tsp TimeStampRequestGenerator setReqPolicy

Introduction

In this page you can find the example usage for org.bouncycastle.tsp TimeStampRequestGenerator setReqPolicy.

Prototype

public void setReqPolicy(ASN1ObjectIdentifier reqPolicy) 

Source Link

Usage

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

License:Open Source License

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from   ww w.ja v a2s  . c  o m*/
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = signerId.getIssuer();
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();
    X509Certificate certificate = signerCert;
    do {
        LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal());
        tspCertificateChain.add(certificate);
        if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
            break;
        }
        String aki = Hex.encodeHexString(getAuthorityKeyId(certificate));
        certificate = certificateMap.get(aki);
    } while (null != certificate);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

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()/*  w w w . ja v  a2s . c o  m*/
 */
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  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:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

License:Open Source License

@Override
public TimeStampResponse getTimeStampResponse(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    try {/* w ww  . j  ava  2 s  . com*/
        byte[] respBytes = null;

        // Setup the time stamp request
        TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        TimeStampRequest request = tsqGenerator.generate(algorithm.getOid(), digest, nonce);
        byte[] requestBytes = request.getEncoded();

        // Call the communications layer
        respBytes = getTSAResponse(requestBytes);

        // Handle the TSA response
        TimeStampResponse response = new TimeStampResponse(respBytes);
        return response;

    } catch (TSPException ex) {
        throw new IOException("Invalid TSP response");
    }

}

From source file:eu.europa.ec.markt.dss.validation102853.tsp.OnlineTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    try {//from  w  ww.ja  va2s  . c om

        if (LOG.isTraceEnabled()) {

            LOG.trace("Timestamp digest algorithm: " + digestAlgorithm.getName());
            LOG.trace("Timestamp digest value    : " + DSSUtils.toHex(digest));
        }

        // Setup the time stamp request
        final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }
        final long val = System.currentTimeMillis();
        final BigInteger nonce = BigInteger.valueOf(val);
        final ASN1ObjectIdentifier asn1ObjectIdentifier = digestAlgorithm.getOid();
        final TimeStampRequest request = tsqGenerator.generate(asn1ObjectIdentifier, digest, nonce);
        final byte[] requestBytes = request.getEncoded();

        // Call the communications layer
        byte[] respBytes;
        if (dataLoader != null) {

            respBytes = dataLoader.post(tspServer, requestBytes);
            //if ("base64".equalsIgnoreCase(encoding)) {
            //respBytes = DSSUtils.base64Decode(respBytes);
            //}
        } else {

            respBytes = getTSAResponse(requestBytes);
        }
        // Handle the TSA response
        final TimeStampResponse timeStampResponse = new TimeStampResponse(respBytes);
        LOG.info("Status: " + timeStampResponse.getStatusString());
        final TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
        if (timeStampToken != null) {

            LOG.info("SID: " + timeStampToken.getSID());
        }
        return timeStampToken;
    } catch (TSPException e) {
        throw new DSSException("Invalid TSP response", e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.client.tsp.OnlineTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {
    try {//  w  w  w . ja  va 2s .c o m
        if (logger.isTraceEnabled()) {
            logger.trace("Timestamp digest algorithm: " + digestAlgorithm.getName());
            logger.trace("Timestamp digest value    : " + Hex.encodeHexString(digest));
        }

        // Setup the time stamp request
        final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
        tsqGenerator.setCertReq(true);
        if (policyOid != null) {
            tsqGenerator.setReqPolicy(policyOid);
        }

        ASN1ObjectIdentifier asn1ObjectIdentifier = new ASN1ObjectIdentifier(digestAlgorithm.getOid());
        TimeStampRequest timeStampRequest = null;
        if (nonceSource == null) {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest);
        } else {
            timeStampRequest = tsqGenerator.generate(asn1ObjectIdentifier, digest, nonceSource.getNonce());
        }

        final byte[] requestBytes = timeStampRequest.getEncoded();

        // Call the communications layer
        if (dataLoader == null) {
            dataLoader = new NativeHTTPDataLoader();
        }
        byte[] respBytes = dataLoader.post(tspServer, requestBytes);

        // Handle the TSA response
        final TimeStampResponse timeStampResponse = new TimeStampResponse(respBytes);

        // Validates nonce, policy id, ... if present
        timeStampResponse.validate(timeStampRequest);

        String statusString = timeStampResponse.getStatusString();
        if (statusString != null) {
            logger.info("Status: " + statusString);
        }

        final TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();

        if (timeStampToken != null) {
            logger.info("TSP SID : SN " + timeStampToken.getSID().getSerialNumber() + ", Issuer "
                    + timeStampToken.getSID().getIssuer());
        }

        return timeStampToken;
    } catch (TSPException e) {
        throw new DSSException("Invalid TSP response", e);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.esig.dss.cookbook.mock.MockTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    final String signatureAlgorithm = getSignatureAlgorithm(digestAlgorithm, digest);

    final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);/*from w  w  w  .  j  av  a  2  s .c  om*/

    /**
     * The code below guarantee that the dates of the two successive
     * timestamps are different. This is activated only if timestampDate is provided at
     * construction time
     */
    Date timestampDate_ = new Date();

    if (policyOid != null) {
        tsqGenerator.setReqPolicy(policyOid);
    }

    TimeStampRequest tsRequest = null;
    if (useNonce) {
        final BigInteger nonce = BigInteger.valueOf(random.nextLong());
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest, nonce);
    } else {
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest);
    }

    try {
        final ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).build(key);
        final JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert.getCertificate());

        // that to make sure we generate the same timestamp data for the
        // same timestamp date
        AttributeTable signedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        signedAttributes = signedAttributes.add(PKCSObjectIdentifiers.pkcs_9_at_signingTime,
                new Time(timestampDate_));
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributes);
        AttributeTable unsignedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
                unsignedAttributes);

        final DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);
        sigInfoGeneratorBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(unsignedAttributeGenerator);
        final SignerInfoGenerator sig = sigInfoGeneratorBuilder.build(sigGen, certHolder);

        final DigestCalculator sha1DigestCalculator = DSSRevocationUtils.getSHA1DigestCalculator();

        final TimeStampTokenGenerator tokenGenerator = new TimeStampTokenGenerator(sig, sha1DigestCalculator,
                policyOid);
        final Set<X509Certificate> singleton = new HashSet<X509Certificate>();
        singleton.add(cert.getCertificate());
        tokenGenerator.addCertificates(new JcaCertStore(singleton));
        final TimeStampResponseGenerator generator = new TimeStampResponseGenerator(tokenGenerator,
                TSPAlgorithms.ALLOWED);

        Date responseDate = new Date();
        TimeStampResponse tsResponse = generator.generate(tsRequest, BigInteger.ONE, responseDate);
        final TimeStampToken timeStampToken = tsResponse.getTimeStampToken();
        return timeStampToken;
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    } catch (CertificateEncodingException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    }
}

From source file:org.apache.poi.poifs.crypt.dsig.services.TSPTimeStampService.java

License:Apache License

@SuppressWarnings("unchecked")
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = CryptoFunctions.getMessageDigest(signatureConfig.getTspDigestAlgo());
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from  w  ww . jav  a2s  .c o  m*/
    String requestPolicy = signatureConfig.getTspRequestPolicy();
    if (requestPolicy != null) {
        requestGenerator.setReqPolicy(new ASN1ObjectIdentifier(requestPolicy));
    }
    ASN1ObjectIdentifier digestAlgoOid = mapDigestAlgoToOID(signatureConfig.getTspDigestAlgo());
    TimeStampRequest request = requestGenerator.generate(digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP POST request
    Proxy proxy = Proxy.NO_PROXY;
    if (signatureConfig.getProxyUrl() != null) {
        URL proxyUrl = new URL(signatureConfig.getProxyUrl());
        String host = proxyUrl.getHost();
        int port = proxyUrl.getPort();
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, (port == -1 ? 80 : port)));
    }

    HttpURLConnection huc = (HttpURLConnection) new URL(signatureConfig.getTspUrl()).openConnection(proxy);

    if (signatureConfig.getTspUser() != null) {
        String userPassword = signatureConfig.getTspUser() + ":" + signatureConfig.getTspPass();
        String encoding = DatatypeConverter
                .printBase64Binary(userPassword.getBytes(Charset.forName("iso-8859-1")));
        huc.setRequestProperty("Authorization", "Basic " + encoding);
    }

    huc.setRequestMethod("POST");
    huc.setConnectTimeout(20000);
    huc.setReadTimeout(20000);
    huc.setDoOutput(true); // also sets method to POST.
    huc.setRequestProperty("User-Agent", signatureConfig.getUserAgent());
    huc.setRequestProperty("Content-Type", signatureConfig.isTspOldProtocol() ? "application/timestamp-request"
            : "application/timestamp-query"); // "; charset=ISO-8859-1");

    OutputStream hucOut = huc.getOutputStream();
    hucOut.write(encodedRequest);

    // invoke TSP service
    huc.connect();

    int statusCode = huc.getResponseCode();
    if (statusCode != 200) {
        LOG.log(POILogger.ERROR, "Error contacting TSP server ", signatureConfig.getTspUrl());
        throw new IOException("Error contacting TSP server " + signatureConfig.getTspUrl());
    }

    // HTTP input validation
    String contentType = huc.getHeaderField("Content-Type");
    if (null == contentType) {
        throw new RuntimeException("missing Content-Type header");
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(huc.getInputStream(), bos);
    LOG.log(POILogger.DEBUG, "response content: ", bos.toString());

    if (!contentType.startsWith(signatureConfig.isTspOldProtocol() ? "application/timestamp-response"
            : "application/timestamp-reply")) {
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }

    if (bos.size() == 0) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    TimeStampResponse timeStampResponse = new TimeStampResponse(bos.toByteArray());
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.log(POILogger.DEBUG, "status: " + timeStampResponse.getStatus());
        LOG.log(POILogger.DEBUG, "status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.log(POILogger.DEBUG, "fail info int value: " + failInfo.intValue());
            if (/*PKIFailureInfo.unacceptedPolicy*/(1 << 8) == failInfo.intValue()) {
                LOG.log(POILogger.DEBUG, "unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Name signerCertIssuer = signerId.getIssuer();
    LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber);
    LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    Collection<X509CertificateHolder> certificates = timeStampToken.getCertificates().getMatches(null);

    X509CertificateHolder signerCert = null;
    Map<X500Name, X509CertificateHolder> certificateMap = new HashMap<X500Name, X509CertificateHolder>();
    for (X509CertificateHolder certificate : certificates) {
        if (signerCertIssuer.equals(certificate.getIssuer())
                && signerCertSerialNumber.equals(certificate.getSerialNumber())) {
            signerCert = certificate;
        }
        certificateMap.put(certificate.getSubject(), certificate);
    }

    // TSP signer cert path building
    if (signerCert == null) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new ArrayList<X509Certificate>();
    JcaX509CertificateConverter x509converter = new JcaX509CertificateConverter();
    x509converter.setProvider("BC");
    X509CertificateHolder certificate = signerCert;
    do {
        LOG.log(POILogger.DEBUG, "adding to certificate chain: " + certificate.getSubject());
        tspCertificateChain.add(x509converter.getCertificate(certificate));
        if (certificate.getSubject().equals(certificate.getIssuer())) {
            break;
        }
        certificate = certificateMap.get(certificate.getIssuer());
    } while (null != certificate);

    // verify TSP signer signature
    X509CertificateHolder holder = new X509CertificateHolder(tspCertificateChain.get(0).getEncoded());
    DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator();
    DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder();
    BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider();
    BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder,
            hashAlgoFinder, calculator);
    SignerInformationVerifier verifier = verifierBuilder.build(holder);

    timeStampToken.validate(verifier);

    // verify TSP signer certificate
    if (signatureConfig.getTspValidator() != null) {
        signatureConfig.getTspValidator().validate(tspCertificateChain, revocationData);
    }

    LOG.log(POILogger.DEBUG, "time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.demoiselle.signer.timestamp.connector.TimeStampOperator.java

License:Open Source License

/**
 * Creates a time stamp request, signed with the users's certificate.
 *
 * @param privateKey private key to sign with
 * @param certificates certificate chain
 * @param content  set null if signing only hash
 * @param hash  set null if signing content
 * @return A time stamp request/* ww  w  .j a v  a2  s.c  o m*/
 * @throws CertificateCoreException exception
 */
public byte[] createRequest(PrivateKey privateKey, Certificate[] certificates, byte[] content, byte[] hash)
        throws CertificateCoreException {
    try {
        logger.info(timeStampMessagesBundle.getString("info.timestamp.digest"));
        Digest digest = DigestFactory.getInstance().factoryDefault();
        String varAlgoOid = null;
        String varAlgo = null;
        if (Configuration.getInstance().getSO().toLowerCase().indexOf("indows") > 0) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.winhash"));
            varAlgoOid = TSPAlgorithms.SHA256.getId();
            varAlgo = "SHA256withRSA";
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
        } else {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.linuxhash"));
            varAlgoOid = TSPAlgorithms.SHA512.getId();
            varAlgo = "SHA512withRSA";
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_512);
        }

        byte[] hashedMessage = null;
        if (content != null) {
            hashedMessage = digest.digest(content);
            //logger.info(Base64.toBase64String(hashedMessage));   
        } else {
            hashedMessage = hash;
        }
        logger.info(timeStampMessagesBundle.getString("info.timestamp.prepare.request"));
        TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
        timeStampRequestGenerator
                .setReqPolicy(new ASN1ObjectIdentifier(TimeStampConfig.getInstance().getTSPOid()));
        timeStampRequestGenerator.setCertReq(true);
        BigInteger nonce = BigInteger.valueOf(100);
        timeStampRequest = timeStampRequestGenerator.generate(new ASN1ObjectIdentifier(varAlgoOid),
                hashedMessage, nonce);
        byte request[] = timeStampRequest.getEncoded();
        logger.info(timeStampMessagesBundle.getString("info.timestamp.sign.request"));
        RequestSigner requestSigner = new RequestSigner();
        byte[] signedRequest = requestSigner.signRequest(privateKey, certificates, request, varAlgo);
        return signedRequest;
    } catch (IOException ex) {

        throw new CertificateCoreException(ex.getMessage());
    }
}

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

License:Open Source License

@SuppressWarnings("SleepWhileInLoop") // We are just using the sleep for rate limiting
private void tsaRequest() throws Exception {
    final Random rand = new Random();
    final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    boolean doRun = true;
    do {/*from www.j a  va 2s. c  om*/

        final int nonce = rand.nextInt();

        byte[] digest = new byte[20];
        if (instring != null) {
            final byte[] digestBytes = instring.getBytes("UTF-8");
            final MessageDigest dig = MessageDigest.getInstance(TSPAlgorithms.SHA1.getId(), "BC");
            dig.update(digestBytes);
            digest = dig.digest();
            // When we have given input, we don't want to loop
            doRun = false;
        }
        if (infilestring != null) {
            // TSPAlgorithms constants changed from Strings to ASN1Encoded objects
            digest = digestFile(infilestring, TSPAlgorithms.SHA1.getId());
            doRun = false;
        }
        final byte[] hexDigest = Hex.encode(digest);

        if (LOG.isDebugEnabled()) {
            LOG.debug("MessageDigest=" + new String(hexDigest));
        }

        final TimeStampRequest timeStampRequest;
        if (inreqstring == null) {
            LOG.debug("Generating a new request");
            timeStampRequestGenerator.setCertReq(certReq);
            if (reqPolicy != null) {
                timeStampRequestGenerator.setReqPolicy(new ASN1ObjectIdentifier(reqPolicy));
            }
            timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest,
                    BigInteger.valueOf(nonce));
        } else {
            LOG.debug("Reading request from file");
            timeStampRequest = new TimeStampRequest(readFiletoBuffer(inreqstring));
        }
        final byte[] requestBytes = timeStampRequest.getEncoded();

        if (outreqstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(requestBytes);
            } else {
                outBytes = requestBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outreqstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        keyStoreOptions.setupHTTPS();

        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        DataInputStream input;

        url = new URL(urlstring);

        // Take start time
        final long startMillis = System.currentTimeMillis();
        final long startTime = System.nanoTime();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending request at: " + startMillis);
        }

        urlConn = url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/timestamp-query");

        // Send POST output.
        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.write(requestBytes);
        printout.flush();
        printout.close();

        // Get response data.
        input = new DataInputStream(urlConn.getInputStream());

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b;
        while ((b = input.read()) != -1) {
            baos.write(b);
        }

        // Take stop time
        final long estimatedTime = System.nanoTime() - startTime;

        LOG.info("Got reply after " + TimeUnit.NANOSECONDS.toMillis(estimatedTime) + " ms");

        final byte[] replyBytes = baos.toByteArray();
        if (outrepstring != null) {
            // Store request
            byte[] outBytes;
            if (base64) {
                outBytes = Base64.encode(replyBytes);
            } else {
                outBytes = replyBytes;
            }
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outrepstring);
                fos.write(outBytes);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }

        final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
        timeStampResponse.validate(timeStampRequest);

        LOG.info("TimeStampRequest validated");

        if (LOG.isDebugEnabled()) {
            final Date genTime;
            if (timeStampResponse.getTimeStampToken() != null
                    && timeStampResponse.getTimeStampToken().getTimeStampInfo() != null) {
                genTime = timeStampResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
            } else {
                genTime = null;
            }
            LOG.debug("(Status: " + timeStampResponse.getStatus() + ", " + timeStampResponse.getFailInfo()
                    + "): " + timeStampResponse.getStatusString()
                    + (genTime != null ? (", genTime: " + genTime.getTime()) : "") + "\n");

        }

        if (doRun) {
            Thread.sleep(sleep);
        }
    } while (doRun);
}