Example usage for org.bouncycastle.tsp TimeStampResponse getTimeStampToken

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

Introduction

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

Prototype

public TimeStampToken getTimeStampToken() 

Source Link

Usage

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

License:Open Source License

/**
 * Tests that the signers only accepts requests with their profile.
 *///www  .j  ava  2  s . c o  m
@Test
public void test02AcceptedProfiles() throws Exception {
    TimeStampRequestGenerator gen = new TimeStampRequestGenerator();
    TimeStampRequest req;
    TimeStampResponse res;

    resetDispatchedAuthorizerForAllWorkers();

    // Test that worker1 accepts its profile but not the other
    gen.setReqPolicy(WORKER1_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER1, req);
    assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
    assertEquals("right profile", WORKER1_PROFILE,
            res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
    assertValid(req, res);

    gen.setReqPolicy(WORKER2_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER1, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());
    assertValid(req, res);

    gen.setReqPolicy(WORKER3_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER1, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());
    assertValid(req, res);

    // Test that worker2 accepts its profile but not the other
    gen.setReqPolicy(WORKER2_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER2, req);
    assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
    assertEquals("right profile", WORKER2_PROFILE,
            res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
    assertValid(req, res);

    gen.setReqPolicy(WORKER1_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER2, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());

    gen.setReqPolicy(WORKER3_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER2, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());

    // Test that worker3 accepts its profile but not the other
    gen.setReqPolicy(WORKER3_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER3, req);
    assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
    assertEquals("right profile", WORKER3_PROFILE,
            res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
    assertValid(req, res);

    gen.setReqPolicy(WORKER1_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER3, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());

    gen.setReqPolicy(WORKER2_PROFILE);
    req = gen.generate(TSPAlgorithms.SHA1, new byte[20], createNounce());
    res = requestTimeStamp(WORKER3, req);
    assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
    assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());
}

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

License:Open Source License

/**
 * Tests that requests going through the dispatcher gets the right profiles.
 *///w  w  w .j av a 2 s  . com
@Test
public void test03AcceptedProfilesThroughDispatcher() throws Exception {
    try {
        TimeStampRequestGenerator gen = new TimeStampRequestGenerator();
        TimeStampRequest req;
        TimeStampResponse res;

        setDispatchedAuthorizerForAllWorkers();

        // Test that a request with WORKER1_PROFILE is accepted
        gen.setReqPolicy(WORKER1_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
        assertEquals("right profile", WORKER1_PROFILE,
                res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
        assertValid(req, res);

        // Test that a request with WORKER2_PROFILE is accepted
        gen.setReqPolicy(WORKER2_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
        assertEquals("right profile", WORKER2_PROFILE,
                res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
        assertValid(req, res);

        // Test that a request with WORKER3_PROFILE is accepted
        gen.setReqPolicy(WORKER3_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
        assertEquals("right profile", WORKER3_PROFILE,
                res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
        assertValid(req, res);

        // Test that an unknown profile is not accepted (USEDEFAULTIFMISMATCH=false)
        gen.setReqPolicy(UNSUPPORTED_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
        assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());

        // Test that an unknown profile is not accepted (USEDEFAULTIFMISMATCH=true but profile not known by the default worker)
        gen.setReqPolicy(UNSUPPORTED_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER9, req);
        assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
        assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());
    } finally {
        resetDispatchedAuthorizerForAllWorkers();
    }
}

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

License:Open Source License

/**
 * Tests that requests which does not request a certain profile gets dispatched 
 * to the default worker.//from   w  w w .ja  v a  2s  .  com
 */
@Test
public void test04DefaultWorker() throws Exception {
    try {
        TimeStampRequestGenerator gen = new TimeStampRequestGenerator();
        TimeStampRequest req;
        TimeStampResponse res;

        setDispatchedAuthorizerForAllWorkers();

        // Test that a request with no reqPolicy goes to WORKER1_PROFILE
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
        assertEquals("right profile", WORKER1_PROFILE,
                res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());
        assertValid(req, res);
    } finally {
        resetDispatchedAuthorizerForAllWorkers();
    }
}

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

License:Open Source License

/**
 * Tests the USEDEFAULTIFMISMATCH option which dispatches requests to the 
 * default worker if no mapping matched.
 *///from w  w w . j a  v a 2s  .  c om
@Test
public void test05UseDefaultIfMisMatch() throws Exception {
    try {
        TimeStampRequestGenerator gen = new TimeStampRequestGenerator();
        TimeStampRequest req;
        TimeStampResponse res;

        setDispatchedAuthorizerForAllWorkers();

        // Test that an profile not known by DISPATCHER0 but by a TSUnit1 is not accepted (USEDEFAULTIFMISMATCH=false)
        gen.setReqPolicy(WORKER1_ALTERNATIVE_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER0, req);
        assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
        assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());

        // Test that an profile not known by DISPATCHER9 but by a TSUnit1 is accepted (USEDEFAULTIFMISMATCH=true)
        gen.setReqPolicy(WORKER1_ALTERNATIVE_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER9, req);
        assertEquals("token granted", PKIStatus.GRANTED, res.getStatus());
        assertEquals("right profile", WORKER1_ALTERNATIVE_PROFILE,
                res.getTimeStampToken().getTimeStampInfo().getPolicy().getId());

        // Test that an profile not known by DISPATCHER9 and not by a TSUnit1 is rejected even though USEDEFAULTIFMISMATCH=true
        gen.setReqPolicy(UNSUPPORTED_PROFILE);
        req = gen.generate(TSPAlgorithms.SHA256, new byte[32], createNounce());
        res = requestTimeStamp(DISPATCHER9, req);
        assertEquals("token rejection", PKIStatus.REJECTION, res.getStatus());
        assertEquals(new PKIFailureInfo(PKIFailureInfo.unacceptedPolicy), res.getFailInfo());
    } finally {
        resetDispatchedAuthorizerForAllWorkers();
    }
}

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  ww  .ja 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());
}

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

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest/*from  w w w.jav a2s . c  om*/
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
@Override
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    final ISignRequest sReq = (ISignRequest) signRequest;

    // Check that the request contains a valid TimeStampRequest object.
    if (!(signRequest instanceof GenericSignRequest)) {
        final IllegalRequestException exception = new IllegalRequestException(
                "Recieved request wasn't a expected GenericSignRequest. ");
        throw exception;
    }

    if (!((sReq.getRequestData() instanceof TimeStampRequest) || (sReq.getRequestData() instanceof byte[]))) {
        final IllegalRequestException exception = new IllegalRequestException(
                "Recieved request data wasn't a expected TimeStampRequest. ");
        throw exception;
    }

    if (!validChain) {
        LOG.error("Certificate chain not correctly configured");
        throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
    }

    final ITimeSource timeSrc = getTimeSource();
    if (LOG.isDebugEnabled()) {
        LOG.debug("TimeSource: " + timeSrc.getClass().getName());
    }
    final Date date = timeSrc.getGenTime();
    final BigInteger serialNumber = getSerialNumber();

    // Log values
    logMap.put(ITimeStampLogger.LOG_TSA_TIME, date == null ? null : String.valueOf(date.getTime()));
    logMap.put(ITimeStampLogger.LOG_TSA_SERIALNUMBER, serialNumber.toString(16));
    logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

    GenericSignResponse signResponse = null;
    ICryptoInstance crypto = null;
    try {
        crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        final TimeStampRequest timeStampRequest = new TimeStampRequest(requestbytes);

        // Log values for timestamp request
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CERTREQ,
                String.valueOf(timeStampRequest.getCertReq()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_CRITEXTOIDS,
                String.valueOf(timeStampRequest.getCriticalExtensionOIDs()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_ENCODED,
                new String(Base64.encode(requestbytes, false)));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NONCRITEXTOIDS,
                String.valueOf(timeStampRequest.getNonCriticalExtensionOIDs()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_NOUNCE,
                String.valueOf(timeStampRequest.getNonce()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_VERSION,
                String.valueOf(timeStampRequest.getVersion()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTALGOID,
                timeStampRequest.getMessageImprintAlgOID().getId());
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPREQUEST_MESSAGEIMPRINTDIGEST,
                new String(Base64.encode(timeStampRequest.getMessageImprintDigest(), false)));

        final TimeStampTokenGenerator timeStampTokenGen = getTimeStampTokenGenerator(crypto, timeStampRequest,
                logMap);

        final TimeStampResponseGenerator timeStampResponseGen = getTimeStampResponseGenerator(
                timeStampTokenGen);

        final TimeStampResponse timeStampResponse = timeStampResponseGen.generate(timeStampRequest,
                serialNumber, date, includeStatusString);

        final TimeStampToken token = timeStampResponse.getTimeStampToken();
        final byte[] signedbytes = timeStampResponse.getEncoded();

        // Log values for timestamp response
        if (LOG.isDebugEnabled()) {
            LOG.debug("Time stamp response status: " + timeStampResponse.getStatus() + ": "
                    + timeStampResponse.getStatusString());
        }
        logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS, String.valueOf(timeStampResponse.getStatus()));
        if (timeStampResponse.getFailInfo() != null) {
            logMap.put(ITimeStampLogger.LOG_TSA_PKIFAILUREINFO,
                    String.valueOf(timeStampResponse.getFailInfo().intValue()));
        }
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED,
                new String(Base64.encode(signedbytes, false)));
        logMap.put(ITimeStampLogger.LOG_TSA_PKISTATUS_STRING, timeStampResponse.getStatusString());

        final String archiveId;
        if (token == null) {
            archiveId = serialNumber.toString(16);
        } else {
            archiveId = token.getTimeStampInfo().getSerialNumber().toString(16);
        }

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // Put in log values
        if (date == null) {
            logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, "timeSourceNotAvailable");
        }

        // We were able to fulfill the request so the worker session bean
        // can go on and charge the client
        if (timeStampResponse.getStatus() == PKIStatus.GRANTED) {
            // The client can be charged for the request
            requestContext.setRequestFulfilledByWorker(true);
        } else {
            logMap.put(IWorkerLogger.LOG_PROCESS_SUCCESS, String.valueOf(false));
        }

    } catch (InvalidAlgorithmParameterException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "InvalidAlgorithmParameterException: " + e.getMessage(), e);
        LOG.error("InvalidAlgorithmParameterException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (NoSuchAlgorithmException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "NoSuchAlgorithmException: " + e.getMessage(), e);
        LOG.error("NoSuchAlgorithmException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (NoSuchProviderException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "NoSuchProviderException: " + e.getMessage(), e);
        LOG.error("NoSuchProviderException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertStoreException e) {
        final IllegalRequestException exception = new IllegalRequestException(
                "CertStoreException: " + e.getMessage(), e);
        LOG.error("CertStoreException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (TSPException e) {
        final IllegalRequestException exception = new IllegalRequestException(e.getMessage(), e);
        LOG.error("TSPException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } finally {
        releaseCryptoInstance(crypto, requestContext);
    }

    return signResponse;
}

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

License:Open Source License

@Test
public void test01BasicTimeStamp() throws Exception {
    // Test signing
    final TimeStampResponse response = assertSuccessfulTimestamp(WORKER1, true);

    // Test that it is using the right algorithm
    final TimeStampToken token = response.getTimeStampToken();
    final SignerInformation si = (SignerInformation) token.toCMSSignedData().getSignerInfos().getSigners()
            .iterator().next();/*from   w w  w.ja  v a 2  s .c  om*/
    assertEquals("sha1withrsa", "1.2.840.113549.1.1.1", si.getEncryptionAlgOID());
}

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

License:Open Source License

/**
 * Test successfully doing a TSA request.
 * //from w  w w  .j av a2 s.  c om
 * @param worker Worker ID
 * @param includeSigningTime If the signingTime signed CMS attribute is expected or not
 * @return Time stamp response
 * @throws Exception
 */
private TimeStampResponse assertSuccessfulTimestamp(int worker, final boolean includeSigningTime)
        throws Exception {
    int reqid = random.nextInt();

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

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

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

    assertTrue(reqid == res.getRequestID());

    Certificate signercert = res.getSignerCertificate();

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

    // Validate the signature of the token
    try {
        final SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider("BC").build((X509Certificate) signercert);
        timeStampResponse.getTimeStampToken().validate(infoVerifier);
    } catch (TSPValidationException ex) {
        LOG.error("Token validation failed", ex);
        fail("Token validation failed: " + ex.getMessage());
    }

    // check the signingTime signed attribute
    final AttributeTable attrs = timeStampResponse.getTimeStampToken().getSignedAttributes();
    final Attribute attr = attrs.get(CMSAttributes.signingTime);

    if (includeSigningTime) {
        assertNotNull("Should contain signingTime signed attribute", attr);
    } else {
        assertNull("Should not contain signingTime signed attribute", attr);
    }

    return timeStampResponse;
}

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

License:Open Source License

private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception {
    int reqid = random.nextInt();
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo,
            new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100));

    byte[] requestBytes = timeStampRequest.getEncoded();

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

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

    final CertificateFactory factory = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes())));

    TimeStampResponse timeStampResponse = null;
    try {//  w  w  w. j  a  va 2s .  c  o  m
        // check response
        timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
        timeStampResponse.validate(timeStampRequest);

        if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
            // return early and don't attempt to get a token
            return timeStampResponse.getStatus();
        }

        // check the hash value from the response
        TimeStampToken token = timeStampResponse.getTimeStampToken();
        AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm();
        assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm());

        Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners();

        // there should be one SignerInfo
        assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size());

        for (Object o : signerInfos) {
            SignerInformation si = (SignerInformation) o;

            // test the response signature algorithm
            assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(),
                    si.getDigestAlgOID());
            assertEquals("Timestamp is signed with unexpected signature encryption algorithm",
                    "1.2.840.113549.1.1.1", si.getEncryptionAlgOID());

            final AttributeTable attrs = si.getSignedAttributes();
            final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate);

            assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size());

            TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert);
        }

    } catch (TSPException e) {
        fail("Failed to verify response");
    } catch (IOException e) {
        fail("Failed to verify response");
    }

    final TimeStampToken token = timeStampResponse.getTimeStampToken();

    try {

        token.validate(cert, "BC");

    } catch (TSPException e) {
        fail("Failed to validate response token");
    }

    return timeStampResponse.getStatus();
}

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

License:Open Source License

private void assertTimeNotAvailable(int worker) throws Exception {
    final int reqid = random.nextInt();

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

    final GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

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

    assertTrue(reqid == res.getRequestID());

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

    LOG.info("Response: " + timeStampResponse.getStatusString());

    assertEquals("Token not granted", PKIStatus.REJECTION, timeStampResponse.getStatus());

    assertEquals("PKIFailureInfo.timeNotAvailable", new PKIFailureInfo(PKIFailureInfo.timeNotAvailable),
            timeStampResponse.getFailInfo());

    assertNull("No timestamp token", timeStampResponse.getTimeStampToken());
}