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:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a Default KeyStore/*  w  ww  .j  a  v  a  2  s  .co  m*/
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}

From source file:info.semanticsoftware.semassist.android.intents.ServiceIntent.java

public String execute() {
    Log.d(Constants.TAG, "factory execute for " + pipelineName + " on server " + candidServerURL + " params "
            + RTParams + " input " + inputString);
    if (candidServerURL.indexOf("https") < 0) {
        Log.d(Constants.TAG, "non secure post to " + candidServerURL);
        RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                RTParams, inputString);/*  www  .j  a v  a2 s . com*/
        Representation representation = new StringRepresentation(request.getXML(), MediaType.APPLICATION_XML);
        Representation response = new ClientResource(candidServerURL).post(representation);
        String responseString = "";
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            responseString = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(Constants.TAG, "$$$ " + responseString);
        return responseString;
    } else {
        try {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = SemAssistApp.getInstance().getContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, SemAssistApp.getInstance().getContext().getString(R.string.keystorePassword)
                        .toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            RequestRepresentation request = new RequestRepresentation(SemAssistApp.getInstance(), pipelineName,
                    RTParams, inputString);
            Representation representation = new StringRepresentation(request.getXML(),
                    MediaType.APPLICATION_XML);

            HttpPost post = new HttpPost(candidServerURL);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            String responseString = "";
            while ((string = bufferedreader.readLine()) != null) {
                responseString += string;
            }
            return responseString;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } //else
    return null;
}

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return Client trust store containing exported Nexus certificate
 *//*ww  w  .j  ava2 s.c o m*/
protected KeyStore trustStore() throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream instream = new FileInputStream(
            resolveBaseFile("src/test/it-resources/ssl/client.jks"))) {
        trustStore.load(instream, "password".toCharArray());
    }
    return trustStore;
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

private void createKeyStore(File keyStoreFile) {
    String id = keyStoreFile.getName();
    try {/* w w  w.ja va2  s .c om*/
        KeyStore key_store = KeyStore.getInstance("JKS");
        key_store.load(null, null);
        generateV1Certificate(id, getKsPass(id), key_store);
        saveKeyStore(key_store, keyStoreFile, id);
    } catch (Exception ex) {
        LOG.log(Level.WARNING, null, ex);
    }
}

From source file:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName/*  www .j av a 2 s. co m*/
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

public static void createNewStoreIfNeeded(String fileName, char[] keystorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException {
    File file = new File(fileName);
    if (file != null && file.exists()) {
        return;/*from www  .  j ava  2s .c om*/
    }
    KeyStore ks = KeyStore.getInstance(JCEKS);
    try (OutputStream os = new FileOutputStream(fileName)) {
        ks.load(null, keystorePassword);
        ks.store(os, keystorePassword);
    } catch (IOException e) {
        LOGGER.error("Error while creating the Keystore: {}. Keystore will not be created." + e.getMessage()
                + "\n" + e);
        throw new RuntimeException(e);
    }
}

From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java

/**
 * Sets the context of the Command. This can then be used to do things like
 * get file paths associated with the Activity.
 *
 * @param cordova The context of the main Activity.
 * @param webView The CordovaWebView Cordova is running in.
 *//*  www . ja  v a  2 s.  c om*/

public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    Log.v(TAG, "Init Fingerprint");
    packageName = cordova.getActivity().getApplicationContext().getPackageName();
    mPluginResult = new PluginResult(PluginResult.Status.NO_RESULT);

    if (android.os.Build.VERSION.SDK_INT < 23) {
        return;
    }

    mKeyguardManager = cordova.getActivity().getSystemService(KeyguardManager.class);
    mFingerPrintManager = cordova.getActivity().getApplicationContext()
            .getSystemService(FingerprintManager.class);

    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
        mKeyStore = KeyStore.getInstance(ANDROID_KEY_STORE);

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }

    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
}

From source file:com.vmware.identity.idm.server.ClientCertTestUtils.java

private KeyStore loadKeyStoreWithType(String keyStoreFile, String pass, String storeType) {
    KeyStore ks = null;/*from w w  w.jav a2s  . com*/
    try {
        ks = KeyStore.getInstance(storeType);
        ks.load(getClass().getClassLoader().getResourceAsStream(keyStoreFile), pass.toCharArray());
    } catch (FileNotFoundException fnfe) {
        throw new IllegalArgumentException(String.format("keystore file [%s] not found", keyStoreFile), fnfe);
    } catch (IOException ioe) {
        String errMsg = ioe.getCause() instanceof UnrecoverableKeyException ? "Wrong keystore password" : "";
        throw new IllegalArgumentException(errMsg, ioe);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return ks;
}

From source file:at.diamonddogs.net.SSLHelper.java

private void makeAllTrustManagerForApache() throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
    KeyStore store;// ww w .  j ava 2s .  c  o  m
    store = KeyStore.getInstance(KeyStore.getDefaultType());
    store.load(null, null);
    SSL_FACTORY_APACHE = new AllTrustingApacheSSLFactory(null);
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

/**
 * Creates a NaCl secret key in the local key store ( {@link Config#USEF_HOME_FOLDER} / {@link Config#USEF_CONFIGURATION_FOLDER}
 * / {@link Config#KEYSTORE_FILENAME}). Creates the key store if it does not exist.
 *
 * @param seed Password/*from ww  w  . j  a  v  a2s.  c  o  m*/
 * @return the associate public key.
 */
public byte[] createSecretKey(String seed) {
    if (seed == null) {
        throw new IllegalArgumentException("A seed must be provided in order to create keys!");
    }

    byte[] publicKey = new byte[32];
    byte[] privateKey = new byte[64];

    NaCl.sodium().crypto_sign_ed25519_seed_keypair(publicKey, privateKey, seed.getBytes(UTF_8));
    SecretKey secretKey = new SecretKeySpec(privateKey, ALGORITHM);

    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    try {
        createNewStoreIfNeeded(keystoreFilename, ksPassword);
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);

        SecretKeyEntry secretKeyEntry = new SecretKeyEntry(secretKey);
        ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(ksKeyPassword);

        ks.setEntry(keystorePKAlias, secretKeyEntry, protectionParameter);
        try (OutputStream os = new FileOutputStream(keystoreFilename)) {
            ks.store(os, ksPassword);
        }

    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new RuntimeException(e);
    }
    return publicKey;
}