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:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }/*from  w  ww  .  j  a  v  a  2  s .  c  o  m*/

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}

From source file:psiprobe.controllers.truststore.TrustStoreController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    List<Map<String, String>> certificateList = new ArrayList<>();
    try {/*from  w  w w .  ja  v a 2s .c o  m*/
        String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
        KeyStore ks;
        if (trustStoreType != null) {
            ks = KeyStore.getInstance(trustStoreType);
        } else {
            ks = KeyStore.getInstance("JKS");
        }
        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        if (trustStore != null) {
            try (FileInputStream fis = new FileInputStream(trustStore)) {
                ks.load(fis, trustStorePassword != null ? trustStorePassword.toCharArray() : null);
            }
            Map<String, String> attributes;
            for (String alias : Collections.list(ks.aliases())) {
                attributes = new HashMap<>();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);

                    attributes.put("alias", alias);
                    attributes.put("cn", cert.getSubjectDN().toString());
                    attributes.put("expirationDate",
                            new SimpleDateFormat("yyyy-MM-dd").format(cert.getNotAfter()));
                    certificateList.add(attributes);
                }
            }
        }
    } catch (Exception e) {
        logger.error("There was an exception obtaining truststore: ", e);
    }
    ModelAndView mv = new ModelAndView(getViewName());
    mv.addObject("certificates", certificateList);
    return mv;
}

From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w w w.j av a2 s  .  c o  m
        // KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        /*
        if (this.keystoreUrl != null) {
        KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
        if (LOG.isDebugEnabled()) {
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String)aliases.nextElement();
                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null) {
                    LOG.debug("Certificate chain '" + alias + "':");
                    for (int c = 0; c < certs.length; c++) {
                        if (certs[c] instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate)certs[c];
                            LOG.debug(" Certificate " + (c + 1) + ":");
                            LOG.debug("  Subject DN: " + cert.getSubjectDN());
                            LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                            LOG.debug("  Valid from: " + cert.getNotBefore() );
                            LOG.debug("  Valid until: " + cert.getNotAfter());
                            LOG.debug("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
            }
        }
        keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        */
        if (this.truststoreUrls != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrls, this.truststorePasswords);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(null, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java

/**
 * @param mapping/*w  ww  .  j a  v  a2s  . c  o m*/
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws Exception
 */
public ActionForward exportCertificate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String sel = ((ShowKeyStoreForm) form).getSelectedItem();
    KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore();
    FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil
            .getPageInterceptListenerById(request.getSession(), "fileDownload");
    if (l == null) {
        l = new FileDownloadPageInterceptListener();
        CoreUtil.addPageInterceptListener(request.getSession(), l);
    }
    File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".cer");
    FileOutputStream out = new FileOutputStream(clientCertFile);
    X509Certificate cert = (X509Certificate) systemClientStore.getCertificate(sel);
    out.write(cert.getEncoded());
    out.flush();
    out.close();
    l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream",
            mapping.findForward("success"), "exportCertificate.message", "keystore", sel));
    return mapping.findForward("success");
}

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

@Test
public void testSign() throws Exception {
    LOG.debug("sign");
    // operate//from www . j  a  v a 2s .c om
    Security.addProvider(new HSMProxyProvider());
    KeyStore keyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyTestCredential testCredential = new HSMProxyTestCredential();
    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(
            testCredential.getCredentialPrivateKey(), testCredential.getCredentialCertificate(),
            "http://localhost:8080/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    keyStore.load(keyStoreParameter);

    String alias = keyStore.aliases().nextElement();

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null);
    assertNotNull(privateKey);

    X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);

    signAndVerify(certificate, privateKey, "SHA1withRSA");
    signAndVerify(certificate, privateKey, "SHA256withRSA");
    signAndVerify(certificate, privateKey, "SHA512withRSA");
}

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

@Test
public void testSignPerformance() throws Exception {
    LOG.debug("sign");
    // operate//  www  . j ava  2  s  .c o m
    Security.addProvider(new HSMProxyProvider());
    KeyStore keyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyTestCredential testCredential = new HSMProxyTestCredential();
    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(
            testCredential.getCredentialPrivateKey(), testCredential.getCredentialCertificate(),
            "http://localhost:8080/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    keyStore.load(keyStoreParameter);

    String alias = keyStore.aliases().nextElement();

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null);
    assertNotNull(privateKey);

    X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);

    final int TEST_COUNT = 40;
    int count = TEST_COUNT;
    long t0 = System.currentTimeMillis();
    while (count > 0) {
        signAndVerify(certificate, privateKey, "SHA1withRSA");
        count--;
    }
    long t1 = System.currentTimeMillis();
    LOG.debug("dt: " + (t1 - t0) / TEST_COUNT);
}

From source file:org.wso2.carbon.apimgt.keymgt.token.AbstractJWTGenerator.java

/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param endUserName - The end user name
 * @throws APIManagementException//from ww w  .ja  v  a2s . c o  m
 */
private String addCertToHeader(String endUserName) throws APIManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);
        Certificate publicCert;

        if (!(publicCerts.containsKey(tenantId))) {
            //get tenant's key store manager
            APIUtil.loadTenantRegistry(tenantId);
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore;
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                //keyStore = tenantKSM.getPrimaryKeyStore();
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        //generate the SHA-1 thumbprint of the certificate
        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        if (publicCert != null) {
            byte[] der = publicCert.getEncoded();
            digestValue.update(der);
            byte[] digestInBytes = digestValue.digest();
            Base64 base64 = new Base64(true);
            String base64UrlEncodedThumbPrint = base64.encodeToString(digestInBytes).trim();
            StringBuilder jwtHeader = new StringBuilder();
            //Sample header
            //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"a_jhNus21KVuoFx65LmkW2O_l10"}
            //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"}
            jwtHeader.append("{\"typ\":\"JWT\",");
            jwtHeader.append("\"alg\":\"");
            jwtHeader.append(getJWSCompliantAlgorithmCode(signatureAlgorithm));
            jwtHeader.append("\",");

            jwtHeader.append("\"x5t\":\"");
            jwtHeader.append(base64UrlEncodedThumbPrint);
            jwtHeader.append('\"');

            jwtHeader.append('}');
            return jwtHeader.toString();
        } else {
            String error = "Error in obtaining tenant's keystore";
            throw new APIManagementException(error);
        }

    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error, e);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error, e);
    } catch (NoSuchAlgorithmException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error, e);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error, e);
    }
}

From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java

/**
 * Tests request for a pkcs12/*from ww w .  j  a  v a 2s .  com*/
 * 
 * @throws Exception error
 */
@Test
public void test01RequestPKCS12() throws Exception {
    log.trace(">test01RequestPKCS12()");

    // find a CA (TestCA?) create a user
    // Send certificate request for a server generated PKCS12
    setupUser(SecConst.TOKEN_SOFT_P12);
    setupUserStatus(EndEntityConstants.STATUS_NEW);

    // POST the OCSP request
    URL url = new URL(httpReqPath + '/' + resourceReq);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    OutputStream os = con.getOutputStream();
    os.write(("user=" + TEST_USERNAME + "&password=foo123&keylength=2048").getBytes("UTF-8"));
    os.close();
    assertEquals("Response code", 200, con.getResponseCode());
    // Some appserver (Weblogic) responds with
    // "application/x-pkcs12; charset=UTF-8"
    String contentType = con.getContentType();
    boolean contentTypeIsPkcs12 = contentType.startsWith("application/x-pkcs12");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // This works for small requests, and PKCS12 requests are small
    InputStream in = con.getInputStream();
    int b = in.read();
    while (b != -1) {
        baos.write(b);
        b = in.read();
    }
    baos.flush();
    in.close();
    byte[] respBytes = baos.toByteArray();
    assertTrue(respBytes.length > 0);
    if (!contentTypeIsPkcs12 && log.isDebugEnabled()) {
        // If the content-type isn't application/x-pkcs12 we like to know what we got back..
        log.debug(new String(respBytes));
    }
    assertTrue("contentType was " + contentType, contentTypeIsPkcs12);

    KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    ByteArrayInputStream is = new ByteArrayInputStream(respBytes);
    store.load(is, "foo123".toCharArray());
    assertTrue(store.containsAlias("ReqTest"));
    X509Certificate cert = (X509Certificate) store.getCertificate("ReqTest");
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
        assertEquals(2048, rsapk.getModulus().bitLength());
    } else {
        assertTrue("Public key is not RSA", false);
    }

    log.trace("<test01RequestPKCS12()");
}

From source file:org.wso2.carbon.appmgt.gateway.token.AbstractJWTGenerator.java

/**
 * Helper method to get public certificate for specific tenant.
 *
 * @param endUserName End user name/*from w ww  . j  a  va 2  s  .  c  om*/
 * @param tenantId Tenant id
 * @return public certificate
 * @throws AppManagementException on error while trying to get public certificate
 */
private Certificate getPublicCertificate(String endUserName, int tenantId) throws AppManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
    try {
        Certificate publicCert = publicCertificate.get(tenantId);

        if (publicCert == null) {
            /* Get tenant's key store manager */
            KeyStoreManager tenantKSM = getKeyStoreManager(tenantId);
            KeyStore keyStore = null;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                /* Derive key store name */
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCertificate.put(tenantId, publicCert);
            }
        }
        return publicCert;
    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's " + tenantId + " keystore";
        throw new AppManagementException(error, e);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public certificate thumbprint for tenant " + tenantId;
        throw new AppManagementException(error, e);
    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm " + signatureAlgorithm + " not found.";
        throw new AppManagementException(error, e);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's " + tenantId + " keystore";
        throw new AppManagementException(error, e);
    }
}

From source file:org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator.java

private Certificate getCertificate(String tenantDomain, int tenantId) throws Exception {

    if (tenantDomain == null) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }/*from   www .  ja  va2  s .  c  o  m*/

    if (tenantId == 0) {
        tenantId = OAuth2Util.getTenantId(tenantDomain);
    }

    Certificate publicCert = null;

    if (!(publicCerts.containsKey(tenantId))) {
        // get tenant's key store manager
        KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

        KeyStore keyStore = null;
        if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            // derive key store name
            String ksName = tenantDomain.trim().replace(".", "-");
            String jksName = ksName + ".jks";
            keyStore = tenantKSM.getKeyStore(jksName);
            publicCert = keyStore.getCertificate(tenantDomain);
        } else {
            publicCert = tenantKSM.getDefaultPrimaryCertificate();
        }
        if (publicCert != null) {
            publicCerts.put(tenantId, publicCert);
        }
    } else {
        publicCert = publicCerts.get(tenantId);
    }
    return publicCert;
}