Example usage for java.security.cert CertStore getInstance

List of usage examples for java.security.cert CertStore getInstance

Introduction

In this page you can find the example usage for java.security.cert CertStore getInstance.

Prototype

public static CertStore getInstance(String type, CertStoreParameters params)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException 

Source Link

Document

Returns a CertStore object that implements the specified CertStore type and is initialized with the specified parameters.

Usage

From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {//from  w w w.  j a  v a2  s. c o m
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.josso.auth.scheme.validation.OCSPX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*  ww w  .  j av  a2 s  .co  m*/
        if (_url != null) {
            log.debug("Using the OCSP server at: " + _url);
            Security.setProperty("ocsp.responderURL", _url);
        } else {
            log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension "
                    + "of the certificate");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // init cert store
        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        if (_ocspCert == null) {
            _ocspCert = getCertificate(_ocspResponderCertificateAlias);
        }
        if (_ocspCert != null) {
            certSet.add(_ocspCert);
            CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
            CertStore store = CertStore.getInstance("Collection", storeParams);
            params.addCertStore(store);
            Security.setProperty("ocsp.responderCertSubjectName",
                    _ocspCert.getSubjectX500Principal().getName());
        }

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // activate OCSP
        Security.setProperty("ocsp.enable", "true");

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

/**
 * Internal method to perform a signing operation.
 *
 * @param token Crypto token to use//from  w  w w .ja  va 2  s  .c om
 * @param config Signer configuration to use for the test
 * @param toSign The XML document to sign
 * @param useCertCredential Generate credential for the request from the mocked signer certificate
 * @param username Username to generate a username/password credential in the request context, if null, no credential is passed
 * @return Verification result
 * @throws Exception
 */
private XAdESVerificationResult getVerificationResult(final MockedCryptoToken token, final WorkerConfig config,
        String toSign, final boolean useCertCredential, final String username) throws Exception {
    XAdESSigner instance = new MockedXAdESSigner(token);

    instance.init(4711, config, null, null);

    final RequestContext requestContext = new RequestContext();

    requestContext.put(RequestContext.TRANSACTION_ID, "0000-100-1");

    if (useCertCredential) {
        final CertificateClientCredential cred = new CertificateClientCredential("CN=foo", "123456789abc");

        requestContext.put(RequestContext.CLIENT_CREDENTIAL, cred);
    } else if (username != null) {
        final UsernamePasswordClientCredential cred = new UsernamePasswordClientCredential(username, "foobar");

        requestContext.put(RequestContext.CLIENT_CREDENTIAL, cred);
    }

    GenericSignRequest request = new GenericSignRequest(100, toSign.getBytes("UTF-8"));
    GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext);

    byte[] data = response.getProcessedData();
    final String signedXml = new String(data);
    LOG.debug("signedXml: " + signedXml);

    // Validation: setup
    CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters());
    KeyStore trustAnchors = KeyStore.getInstance("JKS");
    trustAnchors.load(null, "foo123".toCharArray());
    List<Certificate> chain = token.getCertificateChain(ICryptoToken.PURPOSE_SIGN);
    System.out.println("trust anchor: " + chain.get(chain.size() - 1));
    trustAnchors.setCertificateEntry("rootcert", chain.get(chain.size() - 1)); // Simply assume last cert in chain is the trust anchor

    CertificateValidationProvider certValidator = new PKIXCertificateValidationProvider(trustAnchors, false,
            certStore);

    XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
    XadesVerifier verifier = p.newVerifier();

    // Validation: parse
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(new ByteArrayInputStream(data));
    Element node = doc.getDocumentElement();

    XAdESVerificationResult r = verifier.verify(node, new SignatureSpecificVerificationOptions());

    return r;
}

From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java

@Test
public void testProcessData_basicSigningXAdESFormT() throws Exception {
    LOG.info("testProcessData_basicSigningXAdESFormT");

    XAdESSigner instance = new MockedXAdESSigner(tokenRSA);
    WorkerConfig config = new WorkerConfig();

    config.setProperty("XADESFORM", "T");
    config.setProperty("TSA_URL", "http://example.com/?test=5");

    instance.init(4711, config, null, null);
    instance.setTimeStampTokenProviderImplementation(MockedTimeStampTokenProvider.class);

    // reset mock counters
    MockedTimeStampTokenProvider.reset();

    RequestContext requestContext = new RequestContext();
    requestContext.put(RequestContext.TRANSACTION_ID, "0000-100-1");
    GenericSignRequest request = new GenericSignRequest(100, "<test100/>".getBytes("UTF-8"));
    GenericSignResponse response = (GenericSignResponse) instance.processData(request, requestContext);

    byte[] data = response.getProcessedData();
    final String signedXml = new String(data);
    LOG.debug("signedXml: " + signedXml);

    // Validation: setup
    CertStore certStore = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(tokenRSA.getCertificateChain(ICryptoToken.PURPOSE_SIGN)));
    KeyStore trustAnchors = KeyStore.getInstance("JKS");
    trustAnchors.load(null, "foo123".toCharArray());
    trustAnchors.setCertificateEntry("cert", tokenRSA.getCertificate(ICryptoToken.PURPOSE_SIGN));

    CertificateValidationProvider certValidator = new PKIXCertificateValidationProvider(trustAnchors, false,
            certStore);//from   www. j ava  2s  .c om

    XadesVerificationProfile p = new XadesVerificationProfile(certValidator)
            .withTimeStampTokenVerifier(new MockedTimeStampVerificationProvider());
    XadesVerifier verifier = p.newVerifier();

    // Validation: parse
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.parse(new ByteArrayInputStream(data));
    Element node = doc.getDocumentElement();

    XAdESVerificationResult r = verifier.verify(node, new SignatureSpecificVerificationOptions());

    LOG.debug("signature form: " + r.getSignatureForm().name());
    assertEquals("T", r.getSignatureForm().name());
    assertEquals("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", r.getSignatureAlgorithmUri());

    // check that a time stamp token was requested
    assertTrue("Should request a time stamp token", MockedTimeStampTokenProvider.hasRequestedTimeStampToken());

    // check that the time stamp token was verified
    assertTrue("Should try to verify timestamp",
            MockedTimeStampTokenProvider.hasPerformedTimeStampVerification());
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java

/**
 * CMS signature with external data and embedded certificate. The CMS only
 * contains the signature, signing certificate and some certificate
 * selector./* w ww .ja v  a  2  s . c  om*/
 * 
 * @throws Exception
 */
@Test
public void testCmsSignatureWithCertificate() throws Exception {
    // setup
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter);
    byte[] toBeSigned = "hello world".getBytes();

    // operate
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    /*
     * addSigner requires the certificate to be able to calculate the key
     * selector.
     */
    generator.addSigner(keyPair.getPrivate(), certificate, CMSSignedDataGenerator.DIGEST_SHA1);
    List<X509Certificate> certList = new LinkedList<X509Certificate>();
    certList.add(certificate);
    CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));
    generator.addCertificatesAndCRLs(certStore);
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);
    CMSSignedData signedData = generator.generate(content, false, (String) null);

    byte[] cmsSignature = signedData.getEncoded();
    LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject()));

    // verify
    signedData = new CMSSignedData(content, cmsSignature);
    certStore = signedData.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
        SignerInformation signer = iter.next();
        SignerId signerId = signer.getSID();
        LOG.debug("signer: " + signerId);
        X509CertSelector signerConstraints = new JcaX509CertSelectorConverter().getCertSelector(signerId);
        LOG.debug("signerConstraints: " + signerConstraints);
        assertTrue(signerConstraints.match(certificate));
        assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));

        X509Certificate storedCert = (X509Certificate) certStore // TODO FIXME
                .getCertificates(signerConstraints).iterator().next();
        assertEquals(certificate, storedCert);
    }
    LOG.debug("content type: " + signedData.getSignedContentTypeOID());
}