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:com.swisscom.safeconnect.backend.PlumberTask.java

public static HttpClient getNewHttpClient(Context context, HttpParams params) {
    InputStream is = null;//  ww  w . j a va 2 s .  co m
    try {
        synchronized (mKeystoreLock) {
            if (keyStore == null) {
                is = context.getAssets().open("swisscom.bks");
                keyStore = KeyStore.getInstance("BKS");
                keyStore.load(is, "sw1ssc0m".toCharArray());
            }

            if (sslSocketFactory == null) {
                sslSocketFactory = new SwisscomSslSocketFactory(keyStore);
                sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            }

            if (schemeRegistry == null) {
                schemeRegistry = new SchemeRegistry();
                schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            }

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
        }

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            Log.e(Config.TAG, "error", e);
        return new DefaultHttpClient();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                if (BuildConfig.DEBUG)
                    Log.e(Config.TAG, "error", e);
            }
        }
    }
}

From source file:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {//from  w w  w  .j  a  va2  s  . c  o m
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {//from w ww  .  j  av a 2s .  c o  m
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

public HttpClient createHttpClient() {
    try {//from  w ww  .  j  av a 2s  .co  m
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        final SSLSocketFactory sf = new IISSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*from  w w w  .  j  av  a2s.c o m*/
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}

From source file:com.openmeap.util.SSLUtils.java

public static KeyStore loadKeyStore(InputStream keyStoreStream, String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(keyStoreStream, password.toCharArray());
    return ks;//from ww w  . j av  a2  s.c  om
}

From source file:sample.tomcat.SslApplicationTests.java

private SSLSocketFactory secureSocketFactory() throws Exception {
    KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    truststore.load(getKeyStoreFile(), "password".toCharArray());
    // setup ssl context
    SSLContext ctx = SSLContexts.custom().loadTrustMaterial(truststore)
            .loadKeyMaterial(truststore, "password".toCharArray()).build();
    return ctx.getSocketFactory();
}

From source file:com.xyproto.archfriend.Web.java

private HttpClient getNewHttpClient() {
    try {//from w w  w  . ja v  a  2s . co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.wialon.remote.ApacheSdkHttpClient.java

private void initDefaultClient() {
    BasicHttpParams httpParams = getBasicHttpParams(DEFAULT_SOCKET_TIMEOUT);
    KeyStore trustStore;//w  ww . j  av  a 2s.  c om
    SSLSocketFactory sf = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        sf = new TrustAllSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (sf != null)
        registry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, registry);
    defaultHttpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
}

From source file:org.structr.android.restclient.StructrConnector.java

private static SSLSocketFactory createSslSocketFactory(Context context, int resourceId,
        String keyStorePassword) {

    try {/*from w w  w  . j ava 2s . c  o m*/
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = context.getResources().openRawResource(resourceId);

        try {
            trusted.load(in, keyStorePassword.toCharArray());

        } finally {
            in.close();
        }

        return new SSLSocketFactory(trusted);

    } catch (Exception e) {
        throw new AssertionError(e);
    }
}