Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:org.digidoc4j.impl.bdoc.BDocContainerTest.java

static X509Certificate getSignerCert(String certFile) {
    try {/* w ww.java2 s .  c  o  m*/
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream stream = new FileInputStream(certFile)) {
            keyStore.load(stream, "test".toCharArray());
        }
        return (X509Certificate) keyStore.getCertificate("1");
    } catch (Exception e) {
        throw new DigiDoc4JException("Loading signer cert failed");
    }
}

From source file:org.openremote.controller.rest.FindCertificateByID.java

protected String getChain(String username) throws Exception {
    username = URLDecoder.decode(username, "UTF-8");
    String rootCAPath = configurationService.getItem("ca_path");
    String keystore = rootCAPath + "/server.jks";

    StringBuffer sb = new StringBuffer();
    sb.append(Constants.STATUS_XML_HEADER);

    sb.append("\n<chain>\n<server>\n");

    try {/*from   w w w . j  ava2s .com*/
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keystore), "password".toCharArray());
        Certificate certificate = ks.getCertificate(CA_ALIAS);
        sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
    } catch (KeyStoreException e) {
        logger.error(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage());
    } catch (CertificateException e) {
        logger.error(e.getMessage());
    }

    sb.append("</server>\n<client>\n");

    try {
        Certificate certificate = clientService.getClientCertificate(username);
        if (certificate != null) {
            // Check client certificate
            //if(clientService.(dn, datum)
            X509Certificate x509cert = (X509Certificate) certificate;
            Principal dname = x509cert.getSubjectDN();
            Date notAfterDate = x509cert.getNotAfter();

            if (clientService.isClientValid(dname.toString())) {
                if (clientService.isClientDateValid(notAfterDate)) {
                    sb.append(new String(Base64.encodeBase64(certificate.getEncoded())));
                } else {
                    throw new Exception(ERROR_DATE_EXPIRED);
                }
            } else {
                throw new Exception(ERROR_INVALID_DN);
            }
        } else {
            logger.error("Client certificate is not found/null.");
        }
    } catch (CertificateEncodingException e) {
        logger.error(e.getMessage());
    }

    sb.append("</client>\n</chain>");
    sb.append(Constants.STATUS_XML_TAIL);

    return sb.toString();
}

From source file:test.be.fedict.eid.applet.MSCAPITest.java

@Test
public void testMSCAPI() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("Windows-MY");
    keyStore.load(null, null);//from w ww.j  av  a 2s  .  co m
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testAliasesAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate//ww w.j a  va  2s.  c  o m
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        LOG.debug("alias: " + aliasesEnum.nextElement());
    }
}

From source file:com.thoughtworks.go.security.AuthSSLX509TrustManagerFactory.java

private void logKeyStore(KeyStore store) throws KeyStoreException {
    Enumeration aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        LOG.debug("Trusted certificate '" + alias + "':");
        Certificate trustedcert = store.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            LOG.trace("  Subject DN: " + cert.getSubjectDN());
            LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.trace("  Valid from: " + cert.getNotBefore());
            LOG.trace("  Valid until: " + cert.getNotAfter());
            LOG.trace("  Issuer: " + cert.getIssuerDN());
        }//from   w  w w  . ja  va  2s . c  o  m
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.EHealthSTSClientTest.java

@Test
public void testClient() throws Exception {
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//from w  w w  .  j  a  v a 2s  .c  o m
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertionElement = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertionElement);

    LOG.debug("assertion: " + toString(assertionElement));

    LOG.debug("not after: " + client.getNotAfter(assertionElement));
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testSignAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate/*from   ww w . j ava2  s.c  om*/
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            "https://www.e-contract.be/hsm-proxy-ws/dss",
            // "http://localhost/hsm-proxy-ws/dss",
            new MyHSMProxyAudit());
    keyStoreParameter.setProxy("proxy.yourict.net", 8080);
    hsmProxyKeyStore.load(keyStoreParameter);

    PrivateKey hsmPrivateKey = (PrivateKey) hsmProxyKeyStore.getKey("alias", null);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(hsmPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    assertNotNull(signatureValue);
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testGetCertificateAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate/*w  w  w  .ja va2  s  .co m*/
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias);
        assertNotNull(certificate);
        LOG.debug("certificate: " + certificate);
        assertTrue(hsmProxyKeyStore.containsAlias(alias));
        Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias);
        assertNotNull(certificateChain);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null);
        assertNotNull(privateKeyEntry);
    }
}

From source file:org.lockss.util.TestKeyStoreUtil.java

void assertPrivateKs(File file, String pass, String alias) throws Exception {
    KeyStore ks = loadKeyStore("jceks", file, alias);
    List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
    assertEquals(2, aliases.size());/* w w w  .j  a  v a  2  s. c o  m*/
    Certificate cert = ks.getCertificate(alias + ".crt");
    assertNotNull(cert);
    assertEquals("X.509", cert.getType());
    assertTrue(ks.isKeyEntry(alias + ".key"));
    assertTrue(ks.isCertificateEntry(alias + ".crt"));
    Key key = ks.getKey(alias + ".key", pass.toCharArray());
    assertNotNull(key);
    assertEquals("RSA", key.getAlgorithm());
}

From source file:test.integ.be.e_contract.mycarenet.cxf.SyncClientTest.java

@Test
public void testEchoViaInvoke() throws Exception {
    // setup/*from  ww  w  . j av a  2s .c o  m*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        SyncClient syncClient = new SyncClient("https://pilot.mycarenet.be/services/care-provider/sync",
                sessionKey, packageLicenseKey);

        String result = syncClient
                .invoke("<EchoRequest xmlns=\"urn:be:cin:mycarenet:1.0:sync:types\" xml:lang=\"en\">"
                        + "<test/>" + "</EchoRequest>");

        // verify
        LOG.debug("result: " + result);
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}