Example usage for org.bouncycastle.tsp TimeStampResponse TimeStampResponse

List of usage examples for org.bouncycastle.tsp TimeStampResponse TimeStampResponse

Introduction

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

Prototype

TimeStampResponse(DLSequence dlSequence) throws TSPException, IOException 

Source Link

Usage

From source file:org.linagora.linshare.core.service.impl.TimeStampingServiceImpl.java

License:Open Source License

private TimeStampResponse getTimeStamp(URI uriTSA, byte[] sha1Digest) throws TSPException {
    TimeStampResponse response = null;//  ww  w .java2  s .  c  om

    ByteArrayInputStream bis = null;
    OutputStream out = null;

    try {

        TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

        SecureRandom randomGenerator = SecureRandom.getInstance("SHA1PRNG");
        long nonce = randomGenerator.nextLong();

        // request with digestAlgorithmOID, byte[] digest, java.math.BigInteger nonce
        TimeStampRequest request = reqGen.generate(TSPAlgorithms.SHA1, sha1Digest, BigInteger.valueOf(nonce));

        byte[] reqData = request.getEncoded();

        HttpURLConnection conn = (HttpURLConnection) uriTSA.toURL().openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        conn.setRequestProperty("Content-Type", "application/timestamp-query");
        conn.setRequestProperty("Content-Length", Long.toString(reqData.length));
        conn.setRequestMethod("POST");

        out = conn.getOutputStream();
        bis = new ByteArrayInputStream(reqData);

        byte[] tab = new byte[1024];

        int lu = bis.read(tab);

        while (lu >= 0) {
            out.write(tab, 0, lu);
            lu = bis.read(tab);
        }

        out.flush();

        int returnCode = conn.getResponseCode();

        if (returnCode == HttpURLConnection.HTTP_OK) {

            InputStream in = conn.getInputStream();
            response = new TimeStampResponse(in);

            response.validate(request); // if it fails a TSPException is raised
        } else {
            //404 or 500 ...
            throw new TSPException("service TSA is not available");
        }
    } catch (ProtocolException e) {
        throw new TSPException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TSPException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new TSPException(e.getMessage(), e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }
    }

    return response;
}

From source file:org.signserver.cli.ArchivingCLITest.java

License:Open Source License

/**
 * Tests archiving commands for timestamp token.
 *//*from   w w  w  .  j av  a  2  s .  c  o m*/
@Test
public void testSetupTimeStamp() throws Exception {
    LOG.debug(">testSetupTimeStamp");

    assertTrue(new File(getSignServerHome() + "/res/test/test_add_timestamp_archive_configuration.properties")
            .exists());
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("setproperties",
            getSignServerHome() + "/res/test/test_add_timestamp_archive_configuration.properties"));
    assertPrinted("", cli.getOut(), "Setting the property NAME to timestampSigner1000 for worker 1000");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("removeproperty", TESTTSID, "ARCHIVER0.ARCHIVE_OF_TYPE"));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("reload", "1000"));

    // Test the timestamp client
    TimeStampCommand cmd = new TimeStampCommand();
    assertEquals(CommandLineInterface.RETURN_SUCCESS,
            cmd.execute("http://localhost:8080/signserver/process?workerId=" + TESTTSID, "-instr", "TEST",
                    "-outrep", getSignServerHome() + "/tmp/timestamptest.data"));

    FileInputStream fis = new FileInputStream(getSignServerHome() + "/tmp/timestamptest.data");
    TimeStampResponse tsr = new TimeStampResponse(fis);
    assertTrue(tsr != null);
    String archiveId = tsr.getTimeStampToken().getTimeStampInfo().getSerialNumber().toString(16);
    assertNotNull(archiveId);

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "findfromarchiveid", TESTTSID, archiveId, getSignServerHome() + "/tmp"));
    File datafile = new File(getSignServerHome() + "/tmp/" + archiveId + ".response");
    assertTrue(datafile.exists());
    datafile.delete();
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "findfromrequestip", TESTTSID, "127.0.0.1", getSignServerHome() + "/tmp"));
    datafile = new File(getSignServerHome() + "/tmp/" + archiveId + ".response");
    assertTrue(datafile.exists());

    // clean up for before running the query command
    datafile.delete();

    // test query command
    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS, cli.execute("archive", "query",
            "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria", "archiveid EQ " + archiveId));
    assertPrinted("", cli.getOut(), archiveId + ", ");
    // running without -outpath should NOT result in dumping the data
    assertTrue("Should not write archive data", !datafile.exists());

    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS, cli.execute("archive", "query",
            "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria", "requestIP EQ 127.0.0.1"));
    assertPrinted("", cli.getOut(), "REQUEST, " + TESTTSID + ", , , 127.0.0.1");

    // test running the query command with outputting data
    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "query", "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria",
                    "archiveid EQ " + archiveId, "-outpath", getSignServerHome() + "/tmp"));
    assertPrinted("", cli.getOut(), archiveId + ", ");
    assertPrinted("", cli.getOut(), "Downloaded 1 archive entries");
    // running without -outpath should NOT result in dumping the data
    assertTrue("Should write archive data", datafile.exists());

    // clean up temp file
    datafile.delete();
}

From source file:org.signserver.cli.ArchivingCLITest.java

License:Open Source License

/**
 * Tests archiving commands for timestamping with both request and response
 * archived.// w ww. j av a2 s .  co m
 */
@Test
public void testArchiveRequestAndResponse() throws Exception {
    LOG.debug(">testSetupTimeStamp");

    assertTrue(new File(getSignServerHome() + "/res/test/test_add_timestamp_archive_configuration.properties")
            .exists());
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("setproperties",
            getSignServerHome() + "/res/test/test_add_timestamp_archive_configuration.properties"));
    assertPrinted("", cli.getOut(), "Setting the property NAME to timestampSigner1000 for worker 1000");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("setproperty", TESTTSID, "ARCHIVER0.ARCHIVE_OF_TYPE", "REQUEST_AND_RESPONSE"));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("reload", "1000"));

    // Test the timestamp client
    TimeStampCommand cmd = new TimeStampCommand();
    assertEquals(CommandLineInterface.RETURN_SUCCESS,
            cmd.execute("http://localhost:8080/signserver/process?workerId=" + TESTTSID, "-instr", "TEST",
                    "-outrep", getSignServerHome() + "/tmp/timestamptest.data"));

    FileInputStream fis = new FileInputStream(getSignServerHome() + "/tmp/timestamptest.data");
    TimeStampResponse tsr = new TimeStampResponse(fis);
    assertTrue(tsr != null);
    String archiveId = tsr.getTimeStampToken().getTimeStampInfo().getSerialNumber().toString(16);
    assertNotNull(archiveId);

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "findfromarchiveid", TESTTSID, archiveId, getSignServerHome() + "/tmp"));
    File datafileResponse = new File(getSignServerHome() + "/tmp/" + archiveId + ".response");
    File datafileRequest = new File(getSignServerHome() + "/tmp/" + archiveId + ".request");
    assertTrue(datafileResponse.exists());
    datafileResponse.delete();
    assertTrue(datafileRequest.exists());
    datafileRequest.delete();

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "findfromrequestip", TESTTSID, "127.0.0.1", getSignServerHome() + "/tmp"));
    datafileResponse = new File(getSignServerHome() + "/tmp/" + archiveId + ".response");
    datafileRequest = new File(getSignServerHome() + "/tmp/" + archiveId + ".request");
    assertTrue(datafileResponse.exists());
    assertTrue(datafileRequest.exists());

    // clean up before running the query command
    datafileResponse.delete();
    datafileRequest.delete();

    // test query command
    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS, cli.execute("archive", "query",
            "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria", "archiveid EQ " + archiveId));
    assertPrinted("", cli.getOut(), archiveId + ", ");

    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS, cli.execute("archive", "query",
            "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria", "requestIP EQ 127.0.0.1"));
    assertPrinted("", cli.getOut(), "REQUEST, " + TESTTSID + ", , , 127.0.0.1");
    assertPrinted("", cli.getOut(), "RESPONSE, " + TESTTSID + ", , , 127.0.0.1");

    assertEquals("Command status", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("archive", "query", "-limit", "10", "-criteria", "signerid EQ " + TESTTSID, "-criteria",
                    "archiveid EQ " + archiveId, "-outpath", getSignServerHome() + "/tmp"));
    assertPrinted("", cli.getOut(), "REQUEST, " + TESTTSID + ", , , 127.0.0.1");
    assertPrinted("", cli.getOut(), "RESPONSE, " + TESTTSID + ", , , 127.0.0.1");
    assertPrinted("", cli.getOut(), "Downloaded 2 archive entries");
    assertTrue("Should write request", datafileRequest.exists());
    assertTrue("Should write response", datafileResponse.exists());

    // clean up temp files
    datafileRequest.delete();
    datafileResponse.delete();
}

From source file:org.signserver.cli.SignServerCLITest.java

License:Open Source License

@Test
public void testSetupTimeStamp() throws Exception {

    assertTrue(/*  w w  w  .  j  a  v a  2  s.  com*/
            new File(getSignServerHome() + "/res/test/test_add_timestamp_configuration.properties").exists());
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("setproperties",
            getSignServerHome() + "/res/test/test_add_timestamp_configuration.properties"));
    assertPrinted("", cli.getOut(), "Setting the property NAME to timestampSigner1000 for worker 1000");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("reload", "1000"));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("getstatus", "complete", TESTTSID));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("setproperty", TESTTSID, "TESTKEY", "TESTVALUE"));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("getstatus", "complete", TESTTSID));

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("reload", TESTTSID));
    assertPrinted("", cli.getOut(), "SignServer reloaded successfully");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("getstatus", "complete", TESTTSID));
    assertPrinted("", cli.getOut(), "NAME=timestampSigner1000");
    assertPrinted("", cli.getOut(), "TESTKEY");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("reload", TESTTSID));
    assertPrinted("", cli.getOut(), "SignServer reloaded successfully");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("getstatus", "complete", TESTTSID));
    assertPrinted("", cli.getOut(), "NAME=timestampSigner1000");

    // Test token operations
    assertFalse("", CommandLineInterface.RETURN_SUCCESS == cli.execute("activatesigntoken", TESTTSID, "9876"));
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("activatesigntoken", TESTTSID, "1234"));
    assertPrinted("", cli.getOut(), "Activation of worker was successful");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("deactivatesigntoken", TESTTSID));
    assertPrinted("", cli.getOut(), "Deactivation of worker was successful");

    // Test operations by name
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("activatecryptotoken", "timestampSigner1000", "1234"));
    assertPrinted("", cli.getOut(), "Activation of worker was successful");
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("activatecryptotoken", "TIMESTAMPSIGNER1000", "1234"));
    assertFalse("", CommandLineInterface.RETURN_SUCCESS == cli.execute("activatecryptotoken",
            "TIMESTAMPSIGNER2000", "1234"));

    // Test authorized clients
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("addauthorizedclient", "TIMESTAMPSIGNER1000", "EF34242D2324", "CN=Test Root CA"));
    assertPrinted("", cli.getOut(), "Adding the client certificate with sn ef34242d2324");
    // test adding an authorized client via a PEM file
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("addauthorizedclient",
            "TIMESTAMPSIGNER1000", getSignServerHome() + "/res/test/dss10/dss10_signer1.pem"));
    System.out.println("Out: " + cli.getOut().toString());
    assertPrinted("", cli.getOut(), "Adding the client certificate with sn 41935ada62ee0e8a and "
            + "issuerDN : CN=DSS Root CA 10,OU=Testing,O=SignServer,C=SE");
    // test adding an authorized client via a DER file
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("addauthorizedclient",
            "TIMESTAMPSIGNER1000", getSignServerHome() + "/res/test/dss10/dss10_signer2.der"));
    assertPrinted("", cli.getOut(), "Adding the client certificate with sn 53f6992d081248a and "
            + "issuerDN : CN=DSS Root CA 10,OU=Testing,O=SignServer,C=SE");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("listauthorizedclients", "TIMESTAMPSIGNER1000"));
    assertPrinted("", cli.getOut(), "ef34242d2324, CN=Test Root CA");

    // test adding an authorized client specifying leading zero in SN
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("addauthorizedclient", "TIMESTAMPSIGNER1000", "0FF34242D2324", "CN=Test Root CA"));
    assertPrinted("", cli.getOut(), "Adding the client certificate with sn ff34242d2324");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("listauthorizedclients", "TIMESTAMPSIGNER1000"));
    assertPrinted("", cli.getOut(), "ff34242d2324, CN=Test Root CA");

    // test removing authorized client specifying SN with leading 0 and upper-case
    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("removeauthorizedclient", "TIMESTAMPSIGNER1000", "0FF34242D2324", "CN=Test Root CA"));
    assertPrinted("", cli.getOut(), "Client Removed");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("removeauthorizedclient", "TIMESTAMPSIGNER1000", "EF34242D2324", "CN=Test Root CA"));
    assertPrinted("", cli.getOut(), "Client Removed");

    assertEquals("", CommandLineInterface.RETURN_SUCCESS,
            cli.execute("listauthorizedclients", "TIMESTAMPSIGNER1000"));
    assertNotPrinted("", cli.getOut(), "ef34242d2324, CN=Test Root CA");

    // Dump
    assertEquals("", CommandLineInterface.RETURN_SUCCESS, cli.execute("dumpproperties", "TIMESTAMPSIGNER1000",
            getSignServerHome() + "/tmp/testdump.properties"));
    assertPrinted("", cli.getOut(), "Properties successfully dumped into file");

    Properties props = new Properties();
    props.load(new FileInputStream(getSignServerHome() + "/tmp/testdump.properties"));
    assertNotNull(props.get("WORKER1000.AUTHTYPE"));

    // Test the timestamp client
    TimeStampCommand cmd = new TimeStampCommand();
    assertEquals(CommandLineInterface.RETURN_SUCCESS,
            cmd.execute("http://localhost:8080/signserver/process?workerId=" + TESTTSID, "-instr", "TEST",
                    "-outrep", getSignServerHome() + "/tmp/timestamptest.data"));

    FileInputStream fis = new FileInputStream(getSignServerHome() + "/tmp/timestamptest.data");
    TimeStampResponse tsr = new TimeStampResponse(fis);
    assertTrue(tsr != null);
    String archiveId = tsr.getTimeStampToken().getTimeStampInfo().getSerialNumber().toString(16);
    assertNotNull(archiveId);
}

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;//w w w.  j a  v  a  2 s .  com
    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 {//from  ww w .ja  v  a 2s. c  o m
        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: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 {// w w  w .  j  ava 2s.c  o m

        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);
}

From source file:org.signserver.client.cli.TimeStampCommandTest.java

License:Open Source License

/**
 * Tests getting a timestamp.//from  w  w  w .j ava2s  .  c  om
 * @throws Exception
 */
@Test
public void test02requestATimestamp() throws Exception {
    File responseFile = File.createTempFile("signserver-" + this.getClass().getName() + "-response1-", null);
    responseFile.deleteOnExit();
    assertEquals(CommandLineInterface.RETURN_SUCCESS,
            cli.execute("timestamp", "-instr", "Any text we want to have a timestamp for...123", "-outrep",
                    responseFile.getAbsolutePath(), "-url",
                    "http://localhost:8080/signserver/tsa?workerId=" + getSignerIdTimeStampSigner1()));
    InputStream in = null;
    try {
        in = new FileInputStream(responseFile);
        TimeStampResponse res = new TimeStampResponse(in);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            } // NOPMD
        }
    }
}

From source file:org.signserver.client.cli.TimeStampCommandTest.java

License:Open Source License

/**
 * Tests getting a timestamp over HTTPS (port 8442).
 * @throws Exception/*from   ww w . j av  a2 s. co m*/
 */
@Test
public void test02requestATimestampOverHTTPS() throws Exception {
    File responseFile = File.createTempFile("signserver-" + this.getClass().getName() + "-response2-", null);
    responseFile.deleteOnExit();
    assertEquals(CommandLineInterface.RETURN_SUCCESS,
            cli.execute("timestamp", "-instr", "Any text we want to have a timestamp for...123", "-outrep",
                    responseFile.getAbsolutePath(), "-url",
                    "https://" + getHTTPHost() + ":" + getPublicHTTPSPort() + "/signserver/tsa?workerId="
                            + getSignerIdTimeStampSigner1(),
                    "-truststore", getTestUtils().getTruststoreFile().getAbsolutePath(), "-truststorepwd",
                    getTestUtils().getTrustStorePassword()));
    InputStream in = null;
    try {
        in = new FileInputStream(responseFile);
        TimeStampResponse res = new TimeStampResponse(in);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            } // NOPMD
        }
    }
}

From source file:org.signserver.module.tsa.RequestedPolicyDispatcherTest.java

License:Open Source License

private void assertSuccessfulTimestamp(int worker) throws Exception {
    final int reqid = random.nextInt();
    final BigInteger nounce = createNounce();

    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, new byte[20],
            nounce);// w w  w.  j  a  v  a  2 s .c om
    byte[] requestBytes = timeStampRequest.getEncoded();

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

    final GenericSignResponse res = (GenericSignResponse) workerSession.process(worker, signRequest,
            new RequestContext());

    assertEquals("Request ID", reqid, res.getRequestID());

    Certificate signercert = res.getSignerCertificate();
    assertNotNull("contains certificate", signercert);

    final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
    timeStampResponse.validate(timeStampRequest);

    assertEquals("Token granted", PKIStatus.GRANTED, timeStampResponse.getStatus());
    assertNotNull("Got timestamp token", timeStampResponse.getTimeStampToken());
}