Example usage for java.security KeyStore load

List of usage examples for java.security KeyStore load

Introduction

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

Prototype

public final void load(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Loads this KeyStore from the given input stream.

Usage

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {/*from  w  w w . ja v a 2 s  . co  m*/
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, String filename) {
    try {/*ww  w.  j a  v  a 2s  . c om*/
        AsyncHttpClient client = new AsyncHttpClient();
        FileEntity fe = null;
        fe = new FileEntity(new File(filename), "audio/wav");

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), fe, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, byte[] bb) {
    try {// ww  w  .j av  a2s .  c  om
        AsyncHttpClient client = new AsyncHttpClient();
        ByteArrayEntity bae = null;
        bae = new ByteArrayEntity(bb);
        bae.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/octet-stream"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), bae, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:com.terradue.warhol.auth.ssl.SslAuthenticationConfiguration.java

private KeyManager[] fromSslKeyAndCertificate(String publicCertificateLocation, String provateKeyLocation,
        String sslPassword) {/*from w  w  w.  j  a v  a 2s .c om*/
    File publicCertificate = checkFile(publicCertificateLocation);
    File privateKey = checkFile(provateKeyLocation);

    char[] password;
    if (sslPassword != null) {
        password = sslPassword.toCharArray();
    } else {
        password = new char[] {};
    }

    try {
        final KeyStore store = new KeyMaterial(publicCertificate, privateKey, password).getKeyStore();
        store.load(null, password);

        // initialize key and trust managers -> default behavior
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        // password for key and store have to be the same IIRC
        keyManagerFactory.init(store, password);
        return keyManagerFactory.getKeyManagers();
    } catch (Exception e) {
        throw new IllegalStateException("Impossible to initialize SSL certificate/key", e);
    }
}

From source file:org.syslog_ng.elasticsearch_v2.client.http.ESHttpsClient.java

private void loadKeyStore(KeyStore keyStore, String path, String password) {
    try {/*from w  w w .j  a va2  s . co  m*/
        keyStore.load(new FileInputStream(path), password.toCharArray());
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new ESHttpClient.HttpClientBuilderException("Failed to load KeyStore", e);
    }
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, JSONObject json) {
    try {// w  w w. ja v a2s  .  com
        AsyncHttpClient client = new AsyncHttpClient();
        StringEntity se = null;
        try {
            se = new StringEntity(json.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), se, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

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

public byte[] loadSecretKey() {
    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    Key key = null;/*from   ww w .  j  a va2  s.com*/
    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);
        key = ks.getKey(keystorePKAlias, ksKeyPassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException e) {
        LOGGER.error("Exception occured during the loading of the secret key. {}", e);
        throw new RuntimeException(e);
    }
    if (key == null) {
        return new byte[0];
    }
    LOGGER.info("Algorithm: " + key.getAlgorithm());
    LOGGER.info("Format: " + key.getFormat());
    return key.getEncoded();
}

From source file:com.peopleapi.RegisterWithApi.java

private DefaultHttpClient getNewHttpClient() {
    //I mocked out a key store, you will want to generate a real store. this is for testing only!
    try {// w w  w. ja v  a2s . c om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.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.silverpeas.util.security.SilverpeasX509TrustManager.java

public SilverpeasX509TrustManager(String trustStoreFile, char[] password) {
    InputStream fis = null;/*  w w w .j a  va 2s.  c om*/
    try {
        KeyStore trustore = KeyStore.getInstance(KeyStore.getDefaultType());
        fis = new FileInputStream(trustStoreFile);
        trustore.load(fis, password);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(trustore);
        TrustManager tms[] = tmf.getTrustManagers();
        for (TrustManager trustManager : tms) {
            if (trustManager instanceof X509TrustManager) {
                defaultTrustManager = (X509TrustManager) trustManager;
                return;
            }
        }
    } catch (IOException ioex) {
        logger.error("Couldn't load trustore " + trustStoreFile, ioex);
    } catch (GeneralSecurityException secEx) {
        logger.error("Couldn't create trustore " + trustStoreFile, secEx);
    } finally {
        IOUtils.closeQuietly(fis);
    }

}

From source file:com.evolveum.midpoint.init.ConfigurableProtectorFactory.java

public void init() {
    Configuration config = configuration.getConfiguration(PROTECTOR_CONFIGURATION);
    protectorConfig = new ProtectorConfiguration(config);

    //Extract file if not exists
    if (config.getString("midpoint.home") == null) {
        return;//w w w  . ja v  a2 s . c o m
    }

    File ks = new File(protectorConfig.getKeyStorePath());
    if (ks.exists()) {
        return;
    }

    //todo improve
    FileOutputStream fos = null;
    try {
        KeyStore keystore = KeyStore.getInstance("jceks");
        char[] password = "changeit".toCharArray();

        keystore.load(null, password);

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();

        keystore.setKeyEntry("default", secretKey, "midpoint".toCharArray(), null);

        fos = new FileOutputStream(protectorConfig.getKeyStorePath());
        keystore.store(fos, password);
        fos.close();
    } catch (Exception ex) {
        throw new SystemException("Couldn't generate keystore, reason: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}