Example usage for org.bouncycastle.tsp TimeStampToken toCMSSignedData

List of usage examples for org.bouncycastle.tsp TimeStampToken toCMSSignedData

Introduction

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

Prototype

public CMSSignedData toCMSSignedData() 

Source Link

Document

Return the underlying CMSSignedData object.

Usage

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

License:Open Source License

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

    log("running");

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

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

        try {
            TimeStampResponse response = probe(request);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:br.gov.jfrj.siga.cd.TimeStamper.java

License:Open Source License

/**
 * Modyfy PKCS#7 data by adding timestamp
 * /*ww  w .  j  a  v  a  2s .com*/
 * (at) param signedData (at) throws Exception
 */
public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception {
    Collection ss = signedData.getSignerInfos().getSigners();
    SignerInformation si = (SignerInformation) ss.iterator().next();
    TimeStampToken tok = getTimeStampToken(si.getSignature());

    //      CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC");
    Store certs = tok.getCertificates();
    Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs);

    CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls,
            certsAndCrls, certsAndCrls);

    tok = new TimeStampToken(cmssdcrl);

    ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded());
    ASN1Primitive tstDER = asn1InputStream.readObject();
    DERSet ds = new DERSet(tstDER);
    Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds);
    ASN1EncodableVector dv = new ASN1EncodableVector();
    dv.add(a);
    AttributeTable at = new AttributeTable(dv);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    ss.clear();
    ss.add(si);
    SignerInformationStore sis = new SignerInformationStore(ss);
    signedData = CMSSignedData.replaceSigners(signedData, sis);
    return signedData;
}

From source file:ee.ria.xroad.common.signature.TimestampVerifier.java

License:Open Source License

/**
 * Verifies that the time-stamp token is signed by a trusted
 * time-stamping authority./*  w w w  .  j  a v  a 2s. c  o  m*/
 * @param tsToken the time-stamp token
 * @param tspCerts list of TSP certificates
 * @throws Exception if the verification failed
 */
public static void verify(TimeStampToken tsToken, List<X509Certificate> tspCerts) throws Exception {
    if (tspCerts.isEmpty()) {
        throw new CodedException(X_INTERNAL_ERROR, "No TSP service providers are configured.");
    }

    SignerId signerId = tsToken.getSID();

    X509Certificate cert = getTspCertificate(signerId, tspCerts);
    if (cert == null) {
        throw new CodedException(X_INTERNAL_ERROR, "Could not find TSP certificate for timestamp");
    }

    SignerInformation signerInfo = tsToken.toCMSSignedData().getSignerInfos().get(signerId);
    if (signerInfo == null) {
        throw new CodedException(X_INTERNAL_ERROR,
                "Could not get signer information for " + signerId.getSerialNumber());
    }

    SignerInformationVerifier verifier = createVerifier(cert);
    if (!signerInfo.verify(verifier)) {
        throw new CodedException(X_TIMESTAMP_VALIDATION, "Failed to verify timestamp");
    }
}

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

License:Open Source License

public CAdESCertificateSource(final TimeStampToken timeStamp, final CertificatePool certPool) {
    this(timeStamp.toCMSSignedData(),
            ((SignerInformation) timeStamp.toCMSSignedData().getSignerInfos().getSigners().iterator().next()),
            certPool);// ww  w .ja va 2  s  .  c  o  m
}

From source file:eu.europa.esig.dss.validation.CAdESCertificateSource.java

License:Open Source License

public CAdESCertificateSource(final TimeStampToken timeStamp, final CertificatePool certPool) {
    this(timeStamp.toCMSSignedData(),
            (timeStamp.toCMSSignedData().getSignerInfos().getSigners().iterator().next()), certPool);
}

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

License:Open Source License

/**
 * Validate a time stamp//w w w  .  j  av a  2 s.c o m
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();

        int verified = 0;

        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                    .build(cert);
            if (signer.verify(siv)) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
            timeStampToken.validate(siv);
        }

        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));

        //Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID();
            digest.setAlgorithm(algOID.toString());
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }

        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }

    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}

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();/*  ww  w .j  a  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

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 {//from  w  w  w.j a v a 2s. c  om
        // 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

/** Tests issuance of time-stamp token when an EC key is specified. */
@Test//from  w  ww.j  ava2s  .  c o m
public void test20BasicTimeStampECDSA() throws Exception {
    final int workerId = WORKER20;
    try {
        // Setup signer
        final File keystore = new File(getSignServerHome(), "res/test/dss10/dss10_signer5ec.p12");
        if (!keystore.exists()) {
            throw new FileNotFoundException(keystore.getAbsolutePath());
        }
        addP12DummySigner(TimeStampSigner.class.getName(), workerId, "TestTimeStampP12ECDSA", keystore,
                "foo123", "signerec");
        workerSession.setWorkerProperty(workerId, "DEFAULTTSAPOLICYOID", "1.2.3");
        workerSession.setWorkerProperty(workerId, "SIGNATUREALGORITHM", "SHA1WithECDSA");
        workerSession.reloadConfiguration(workerId);

        // Test signing
        TimeStampResponse response = assertSuccessfulTimestamp(WORKER20, true);

        // Test that it is using the right algorithm
        TimeStampToken token = response.getTimeStampToken();
        SignerInformation si = (SignerInformation) token.toCMSSignedData().getSignerInfos().getSigners()
                .iterator().next();
        assertEquals("sha1withecdsa", "1.2.840.10045.4.1", si.getEncryptionAlgOID());

        // Test with SHA256WithECDSA
        workerSession.setWorkerProperty(workerId, "SIGNATUREALGORITHM", "SHA256WithECDSA");
        workerSession.reloadConfiguration(workerId);

        // Test signing
        response = assertSuccessfulTimestamp(WORKER20, true);

        // Test that it is using the right algorithm
        token = response.getTimeStampToken();
        si = (SignerInformation) token.toCMSSignedData().getSignerInfos().getSigners().iterator().next();
        assertEquals("sha256withecdsa", "1.2.840.10045.4.3.2", si.getEncryptionAlgOID());

    } finally {
        removeWorker(workerId);
    }
}

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

License:Open Source License

/** Tests issuance of time-stamp token when an DSA key is specified. */
@Test/*from   w w w .java 2 s.  c  o  m*/
public void test21BasicTimeStampDSA() throws Exception {
    final int workerId = WORKER20;
    try {
        // Setup signer
        final File keystore = new File(getSignServerHome(), "res/test/dss10/dss10_tssigner6dsa.jks");
        if (!keystore.exists()) {
            throw new FileNotFoundException(keystore.getAbsolutePath());
        }
        addJKSDummySigner(TimeStampSigner.class.getName(), workerId, "TestTimeStampJKSDSA", keystore, "foo123",
                "mykey");
        workerSession.setWorkerProperty(workerId, "DEFAULTTSAPOLICYOID", "1.2.3");
        workerSession.setWorkerProperty(workerId, "SIGNATUREALGORITHM", "SHA1WithDSA");
        workerSession.reloadConfiguration(workerId);

        // Test signing
        TimeStampResponse response = assertSuccessfulTimestamp(WORKER20, true);

        // Test that it is using the right algorithm
        TimeStampToken token = response.getTimeStampToken();
        SignerInformation si = (SignerInformation) token.toCMSSignedData().getSignerInfos().getSigners()
                .iterator().next();
        assertEquals("sha1withdsa", "1.2.840.10040.4.3", si.getEncryptionAlgOID());
    } finally {
        removeWorker(workerId);
    }
}