Example usage for org.bouncycastle.tsp TimeStampResponse getStatus

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

Introduction

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

Prototype

public int getStatus() 

Source Link

Usage

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

License:Open Source License

/**
 * Tests that a request including an extension not listed will cause a
 * rejection also when the list of extensions is empty.
 * @throws Exception/*from   www  .  ja va 2s  .c o  m*/
 */
@Test
public void testEmptyAcceptedExtensionsPreventsExtension() throws Exception {
    LOG.info("testEmptyAcceptedExtensionsPreventsExtension");
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    timeStampRequestGenerator.addExtension(new ASN1ObjectIdentifier("1.2.7.9"), false,
            new DEROctetString("Value".getBytes("UTF-8")));
    TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, new byte[20],
            BigInteger.valueOf(100));
    byte[] requestBytes = timeStampRequest.getEncoded();
    GenericSignRequest signRequest = new GenericSignRequest(100, requestBytes);
    final RequestContext requestContext = new RequestContext();
    final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER3, signRequest,
            requestContext);

    final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
    timeStampResponse.validate(timeStampRequest);
    assertEquals("rejection", PKIStatus.REJECTION, timeStampResponse.getStatus());
    assertEquals("unacceptedExtension", PKIFailureInfo.unacceptedExtension,
            timeStampResponse.getFailInfo().intValue());
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void tsSigner() throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + WORKER_TSA, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(WORKER_TSA, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true,
                            new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(WORKER_TSA, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(WORKER_TSA, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(WORKER_TSA);

    // Test active
    List<String> errors = workerSession.getStatus(WORKER_TSA).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, new byte[20],
            BigInteger.valueOf(100));
    byte[] requestBytes = timeStampRequest.getEncoded();
    GenericSignRequest signRequest = new GenericSignRequest(567, requestBytes);
    final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER_TSA, signRequest,
            new RequestContext());
    Certificate signercert = res.getSignerCertificate();
    assertNotNull(signercert);// ww  w . ja  va 2s. c om
    final TimeStampResponse timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
    timeStampResponse.validate(timeStampRequest);

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

From source file:org.signserver.server.tsa.InternalTimeStampTokenFetcher.java

License:Open Source License

public TimeStampToken fetchToken(byte[] imprint, ASN1ObjectIdentifier digestOID) throws IllegalRequestException,
        CryptoTokenOfflineException, SignServerException, TSPException, IOException {
    int workerId;
    try {//from ww w . j  a v  a 2  s. co m
        workerId = Integer.parseInt(workerNameOrId);
    } catch (NumberFormatException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Not a workerId, maybe workerName: " + workerNameOrId);
        }
        workerId = session.getWorkerId(workerNameOrId);
    }

    // Setup the time stamp request
    TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    TimeStampRequest request = tsqGenerator.generate(digestOID, imprint, nonce);
    byte[] requestBytes = request.getEncoded();

    final RequestContext context = new RequestContext();

    if (username != null && password != null) {
        context.put(RequestContext.CLIENT_CREDENTIAL, new UsernamePasswordClientCredential(username, password));
    }

    final ProcessResponse resp = session.process(workerId, new GenericSignRequest(hashCode(), requestBytes),
            context);

    if (resp instanceof GenericSignResponse) {
        final byte[] respBytes = ((GenericSignResponse) resp).getProcessedData();

        TimeStampResponse response = new TimeStampResponse(respBytes);

        TimeStampToken tsToken = response.getTimeStampToken();
        if (tsToken == null) {
            throw new SignServerException("TSA '" + workerNameOrId + "' failed to return time stamp token: "
                    + response.getStatusString());
        }

        if (response.getStatus() != PKIStatus.GRANTED && response.getStatus() != PKIStatus.GRANTED_WITH_MODS) {
            throw new SignServerException("Time stamp token not granted: " + response.getStatusString());
        }
        response.validate(request);

        return tsToken;
    } else {
        throw new SignServerException("Unknown response");
    }

}

From source file:org.signserver.test.performance.impl.TimeStamp.java

License:Open Source License

/**
 * Issue a time stamp request.//from ww  w.j  a  va 2  s  .  c o  m
 * 
 * @return Run time (in ms).
 * @throws TSPException
 * @throws IOException
 * @throws FailedException
 */
private long tsaRequest() throws TSPException, IOException, FailedException {
    final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    final int nonce = random.nextInt();

    byte[] digest = new byte[20];
    final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1, digest,
            BigInteger.valueOf(nonce));
    final byte[] requestBytes = timeStampRequest.getEncoded();

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

    url = new URL(tsaUrl);

    // 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());

    byte[] ba = null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    do {
        if (ba != null) {
            baos.write(ba);
        }
        ba = new byte[input.available()];

    } while (input.read(ba) != -1);

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("Got reply after " + timeInMillis + " ms");
    }

    final byte[] replyBytes = baos.toByteArray();

    final TimeStampResponse timeStampResponse = new TimeStampResponse(replyBytes);
    timeStampResponse.validate(timeStampRequest);
    LOG.debug("TimeStampResponse validated");

    // TODO: Maybe in the future we would like to make the below failure 
    // check configurable or count the failure but without failing the test
    if (timeStampResponse.getStatus() != PKIStatus.GRANTED
            && timeStampResponse.getStatus() != PKIStatus.GRANTED_WITH_MODS) {
        throw new FailedException("Token was not granted. Status was: " + timeStampResponse.getStatus() + " ("
                + timeStampResponse.getStatusString() + ")");
    } else {
        LOG.debug("TimeStampResponse granted");
    }

    return timeInMillis;
}

From source file:org.signserver.test.random.impl.Sign.java

License:Open Source License

private void process(final WorkerSpec signer, final int reqid)
        throws FailedException, IllegalRequestException, CryptoTokenOfflineException, SignServerException {
    final ProcessResponse result;
    final RequestContext requestContext = new RequestContext();
    if (preProcessor != null) {
        preProcessor.preProcess(requestContext);
    }/* w  ww  . j  a  va  2 s  .c o m*/
    switch (signer.getWorkerType()) {
    case xml: {
        // Process
        final GenericSignRequest signRequest = new GenericSignRequest(reqid, TESTXML1.getBytes());
        final ProcessResponse response = workerSession.process(signer.getWorkerId(), signRequest,
                requestContext);

        // Check result
        GenericSignResponse res = (GenericSignResponse) response;
        final byte[] data = res.getProcessedData();
        // Check that we got a signed XML back
        String xml = new String(data);
        if (!xml.contains("xmldsig")) {
            throw new FailedException("Response was not signed: \"" + xml + "\"");
        }
        validateXMLSignature(xml);
        break;
    }
    case tsa: {
        try {
            // Process
            final TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
            final int nonce = random.nextInt();
            final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(TSPAlgorithms.SHA1,
                    new byte[20], BigInteger.valueOf(nonce));
            byte[] requestBytes = timeStampRequest.getEncoded();

            GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);
            final GenericSignResponse res = (GenericSignResponse) workerSession.process(signer.getWorkerId(),
                    signRequest, requestContext);

            // Check result
            if (reqid != res.getRequestID()) {
                throw new FailedException("Expected request id: " + reqid + " but was " + res.getRequestID());
            }

            final Certificate signercert = res.getSignerCertificate();
            if (signercert == null) {
                throw new FailedException("No certificate returned");
            }

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

            if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
                throw new FailedException("Token was not granted: " + timeStampResponse.getStatus());
            }

            if (timeStampResponse.getTimeStampToken() == null) {
                throw new FailedException("No token returned");
            }
            break;
        } catch (TSPException ex) {
            LOG.error("Verification error", ex);
            throw new FailedException("Response could not be verified: " + ex.getMessage());
        } catch (IOException ex) {
            LOG.error("Could not create request", ex);
            throw new FailedException("Could not create request: " + ex.getMessage());
        }
    }
    default:
        throw new IllegalRequestException("Unsupported workerType: " + signer.getWorkerType());
    }
}

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

License:Open Source License

@Override
public final TimeStampTokenRes getTimeStampToken(byte[] tsDigestInput, String digestAlgUri)
        throws TimeStampTokenGenerationException {
    try {/*from   w  ww.  j a  v  a2  s  .  c o  m*/
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        byte[] digest = md.digest(tsDigestInput);

        TimeStampRequest tsRequest = this.tsRequestGenerator.generate(identifierForDigest(digestAlgUri), digest,
                BigInteger.valueOf(System.currentTimeMillis()));
        InputStream responseStream = getResponse(tsRequest.getEncoded());
        TimeStampResponse tsResponse = new TimeStampResponse(responseStream);

        if (tsResponse.getStatus() != PKIStatus.GRANTED
                && tsResponse.getStatus() != PKIStatus.GRANTED_WITH_MODS) {
            throw new TimeStampTokenGenerationException(
                    "Time stamp token not granted. " + tsResponse.getStatusString());
        }
        tsResponse.validate(tsRequest);

        TimeStampToken tsToken = tsResponse.getTimeStampToken();
        return new TimeStampTokenRes(tsToken.getEncoded(), tsToken.getTimeStampInfo().getGenTime());
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenGenerationException("Digest algorithm not supported", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenGenerationException("Invalid time stamp response", ex);
    } catch (IOException ex) {
        throw new TimeStampTokenGenerationException("Encoding error", ex);
    }
}