Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:org.xacml4j.saml.XACMLAuthzDecisionQueryEndpointTest.java

private static KeyStore getKeyStore(String ksType, String resource, String ksPwd) throws Exception {
    InputStream is = null;/*from ww w. j ava  2 s.  com*/
    try {
        is = XACMLAuthzDecisionQueryEndpointTest.class.getResourceAsStream(resource);
        KeyStore ks = KeyStore.getInstance(ksType);
        ks.load(is, ksPwd.toCharArray());
        return ks;
    } finally {
        Closeables.closeQuietly(is);
    }
}

From source file:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }//from w  w w. j  a  v  a 2s.  c o  m
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java

private static KeyStore loadKeyStore(String path, String password) {
    KeyStore ks = null;//from www.j a  va  2 s.  com
    File certKeyFile = new File(path);
    if (!certKeyFile.exists() || !certKeyFile.isFile()) {
        return null;
    }
    char[] pass = password.toCharArray();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(path);
        try {
            ks = KeyStore.getInstance("jks");
            ks.load(fis, pass);
        } catch (Exception e1) {
            try {
                ks = KeyStore.getInstance("bks", bcProvider);
                ks.load(fis, pass);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    } catch (FileNotFoundException e) {
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (Throwable t) {
        }
    }
    return ks;
}

From source file:eu.europa.ec.markt.dss.signature.token.Pkcs12SignatureToken.java

@Override
public List<DSSPrivateKeyEntry> getKeys() throws KeyStoreException {

    List<DSSPrivateKeyEntry> list = new ArrayList<DSSPrivateKeyEntry>();

    InputStream input = null;//from   ww  w .ja  va 2s  .  c o m
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        if (pkcs12Data != null) {
            input = new ByteArrayInputStream(pkcs12Data);
        } else {
            input = new FileInputStream(pkcs12File);
        }

        keyStore.load(input, password);
        PasswordProtection pp = new KeyStore.PasswordProtection(password);
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            if (keyStore.isKeyEntry(alias)) {

                PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, pp);
                list.add(new KSPrivateKeyEntry(entry));
            }
        }
    } catch (Exception e) {
        if (e.getCause() instanceof BadPaddingException) {
            throw new BadPasswordException(MSG.PKCS12_BAD_PASSWORD);
        }
        throw new KeyStoreException(
                "Can't initialize Sun PKCS#12 security provider. Reason: " + getCauseMessage(e), e);
    } finally {
        DSSUtils.closeQuietly(input);
    }
    return list;
}

From source file:org.opendatakit.aggregate.externalservice.GoogleOauth2ExternalService.java

protected static GoogleCredential getCredential(String scopes, CallingContext cc)
        throws ODKExternalServiceCredentialsException {
    try {/*from  w  ww  . ja  v a 2s.co  m*/
        String serviceAccountUser = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.GOOGLE_API_SERVICE_ACCOUNT_EMAIL);
        String privateKeyString = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.PRIVATE_KEY_FILE_CONTENTS);

        if (serviceAccountUser == null || privateKeyString == null || serviceAccountUser.length() == 0
                || privateKeyString.length() == 0) {
            throw new ODKExternalServiceCredentialsException(
                    "No OAuth2 credentials. Have you supplied any OAuth2 credentials on the Site Admin / Preferences page?");
        }

        byte[] privateKeyBytes = Base64.decodeBase64(privateKeyString.getBytes(UTF_CHARSET));

        // TODO: CHANGE TO MORE OPTIMAL METHOD
        KeyStore ks = null;
        ks = KeyStore.getInstance("PKCS12");
        ks.load(new ByteArrayInputStream(privateKeyBytes), "notasecret".toCharArray());
        Enumeration<String> aliasEnum = null;
        aliasEnum = ks.aliases();

        Key key = null;
        while (aliasEnum.hasMoreElements()) {
            String keyName = (String) aliasEnum.nextElement();
            key = ks.getKey(keyName, "notasecret".toCharArray());
            break;
        }
        PrivateKey serviceAccountPrivateKey = (PrivateKey) key;

        HttpClientFactory httpClientFactory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
        HttpTransport httpTransport = httpClientFactory.getGoogleOAuth2Transport();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountUser)
                .setServiceAccountScopes(Collections.singleton(scopes))
                .setServiceAccountPrivateKey(serviceAccountPrivateKey).build();
        credential.refreshToken();
        return credential;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ODKExternalServiceCredentialsException(e);
    }
}

From source file:be.fedict.eid.dss.model.bean.IdentityServiceSingletonBean.java

/**
 * Load identity keystore//from w w  w  .ja  v  a2 s .  co m
 * 
 * @param dssIdentityConfig
 *            identity configuration
 * @return private key entry of identity
 * @throws KeyStoreLoadException
 *             failed to load keystore
 */
public PrivateKeyEntry loadIdentity(DSSIdentityConfig dssIdentityConfig) throws KeyStoreLoadException {

    try {

        if (null == dssIdentityConfig) {
            throw new KeyStoreLoadException("Identity config is empty!");
        }

        FileInputStream keyStoreInputStream = null;
        if (dssIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) {
            Security.addProvider(new SunPKCS11(dssIdentityConfig.getKeyStorePath()));
        } else {
            try {
                keyStoreInputStream = new FileInputStream(dssIdentityConfig.getKeyStorePath());
            } catch (FileNotFoundException e) {
                throw new KeyStoreLoadException("Can't load keystore from config-specified location: "
                        + dssIdentityConfig.getKeyStorePath(), e);
            }
        }

        // load keystore
        KeyStore keyStore = KeyStore.getInstance(dssIdentityConfig.getKeyStoreType().getJavaKeyStoreType());
        char[] password;
        if (null != dssIdentityConfig.getKeyStorePassword()
                && !dssIdentityConfig.getKeyStorePassword().isEmpty()) {
            password = dssIdentityConfig.getKeyStorePassword().toCharArray();
        } else {
            password = null;
        }
        keyStore.load(keyStoreInputStream, password);

        // find entry alias
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new KeyStoreLoadException("no keystore aliases present");
        }

        String alias;
        if (null != dssIdentityConfig.getKeyEntryAlias()
                && !dssIdentityConfig.getKeyEntryAlias().trim().isEmpty()) {
            boolean found = false;
            while (aliases.hasMoreElements()) {
                if (aliases.nextElement().equals(dssIdentityConfig.getKeyEntryAlias())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new KeyStoreLoadException(
                        "no keystore entry with alias \"" + dssIdentityConfig.getKeyEntryAlias() + "\"");
            }
            alias = dssIdentityConfig.getKeyEntryAlias();
        } else {
            alias = aliases.nextElement();
        }
        LOG.debug("keystore alias: " + alias);

        // get keystore entry
        char[] entryPassword;
        if (null != dssIdentityConfig.getKeyEntryPassword()
                && !dssIdentityConfig.getKeyEntryPassword().isEmpty()) {
            entryPassword = dssIdentityConfig.getKeyEntryPassword().toCharArray();
        } else {
            entryPassword = null;
        }

        KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword));
        if (!(entry instanceof PrivateKeyEntry)) {
            throw new KeyStoreLoadException("private key entry expected");
        }
        return (PrivateKeyEntry) entry;
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException(e);
    } catch (CertificateException e) {
        throw new KeyStoreLoadException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreLoadException(e);
    } catch (UnrecoverableEntryException e) {
        throw new KeyStoreLoadException(e);
    } catch (IOException e) {
        throw new KeyStoreLoadException(e);
    }
}

From source file:com.waltz3d.common.httpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./* ww  w . j a va  2s .c o m*/
 */
public AsyncHttpClient() {

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SSLSocketFactory sf = null;
    try {
        sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    //      threadPool = new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();//from ww w.java 2s .c  om

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:com.cerema.cloud2.lib.common.network.NetworkUtils.java

/**
 * Returns the local store of reliable server certificates, explicitly accepted by the user.
 * /*from  www.  jav a 2s  .c o  m*/
 * Returns a KeyStore instance with empty content if the local store was never created.
 * 
 * Loads the store from the storage environment if needed.
 * 
 * @param context                       Android context where the operation is being performed.
 * @return                              KeyStore instance with explicitly-accepted server certificates. 
 * @throws KeyStoreException            When the KeyStore instance could not be created.
 * @throws IOException                  When an existing local trust store could not be loaded.
 * @throws NoSuchAlgorithmException     When the existing local trust store was saved with an unsupported algorithm.
 * @throws CertificateException         When an exception occurred while loading the certificates from the local 
 *                               trust store.
 */
private static KeyStore getKnownServersStore(Context context)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (mKnownServersStore == null) {
        //mKnownServersStore = KeyStore.getInstance("BKS");
        mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
        Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
        if (localTrustStoreFile.exists()) {
            InputStream in = new FileInputStream(localTrustStoreFile);
            try {
                mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }
        } else {
            // next is necessary to initialize an empty KeyStore instance
            mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
        }
    }
    return mKnownServersStore;
}

From source file:com.floragunn.searchguard.test.helper.rest.RestHelper.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(truststore)),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(FileHelper.getAbsoluteFilePathFromClassPath(keystore)),
                "changeit".toCharArray());

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }//w  w w.j a  v a  2 s  .c o m

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);
    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    return hcb.build();
}