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.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }// ww  w. ja v  a2 s.  c o  m

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:no.difi.sdp.client.ObjectMother.java

public static Noekkelpar noekkelpar() {
    try {//from   ww  w.j  a  v a2s  . c  om
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(new ClassPathResource("/selfsigned-keystore.jks").getInputStream(),
                "password1234".toCharArray());
        return Noekkelpar.fraKeyStore(keyStore, "avsender", "password1234");
    } catch (Exception e) {
        throw new RuntimeException("Kunne ikke laste keystore", e);
    }
}

From source file:be.dnsbelgium.rdap.client.RDAPClient.java

public static KeyStore getKeyStoreFromFile(File file, String type, String password) throws KeyStoreException {
    KeyStore result = KeyStore.getInstance(type);
    FileInputStream fis = null;//from  ww w  . j  a  v  a  2 s .  c o  m
    try {
        fis = new FileInputStream(file);
        result.load(fis, password.toCharArray());
    } catch (IOException e) {
        LOGGER.error("Could not load keystore file", e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LOGGER.debug("Could not close keystore file", e);
            }
        }
    }
    return result;
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLKeyManagerFactory.java

public static KeyManager[] getKeyManagers(String storeType, String keystore, String keypass)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManager[] keyManagers;//  ww w .ja v  a2  s.c  om
    if (keystore == null) {
        keyManagers = null;
    } else {
        if (keypass == null) {
            keypass = "";
        }
        KeyStore keyStore = KeyStore.getInstance(storeType);
        keyStore.load(new FileInputStream(keystore), keypass.toCharArray());

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keypass.toCharArray());
        keyManagers = keyFactory.getKeyManagers();
    }
    return keyManagers;
}

From source file:com.nieyue.weixin.ssl.ClientCustomSSL.java

/**
 * ?/*ww  w  . ja  v  a 2 s  . c  o  m*/
 * @return
 * @throws Exception
 */
public static CloseableHttpClient getCloseableHttpClient() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File(ClientCustomSSL.class.getResource("").getPath() + "apiclient_cert.p12"));
    //?
    //FileInputStream instream = new FileInputStream("src/com/nieyue/weixin/ssl/apiclient_cert.p12");
    try {
        keyStore.load(instream, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    @SuppressWarnings("deprecation")
    SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray())
            .build();
    // Allow TLSv1 protocol only
    @SuppressWarnings("deprecation")
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return httpclient;
}

From source file:android.apn.androidpn.server.xmpp.ssl.SSLTrustManagerFactory.java

public static TrustManager[] getTrustManagers(String storeType, String truststore, String trustpass)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    TrustManager[] trustManagers;
    if (truststore == null) {
        trustManagers = null;/*w  ww.  jav a 2  s. c o m*/
    } else {
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if (trustpass == null) {
            trustpass = "";
        }
        KeyStore keyStore = KeyStore.getInstance(storeType);
        keyStore.load(new FileInputStream(truststore), trustpass.toCharArray());
        trustFactory.init(keyStore);
        trustManagers = trustFactory.getTrustManagers();
    }
    return trustManagers;
}

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/*w  w  w. ja  v a  2 s  .c  o m*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:org.cvasilak.jboss.mobile.admin.net.ssl.CustomHTTPClient.java

public static synchronized AbstractHttpClient getHttpClient() {
    try {//  w  w w  .  j a  v a 2  s .  c om
        if (client == null) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new EasySSLSocketFactory(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);

            client = new DefaultHttpClient(ccm, params);
        }
    } catch (Exception e) {
        Log.d(TAG, "unable to create http client", e);
    }

    return client;
}

From source file:com.deying.util.weixin.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    System.out.println("111111111111111111111111111111111111111111111118 ");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12
    try {/*from   www.ja  va  2s.c o m*/
        keyStore.load(instream, "1233374102".toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".toCharArray())//?
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//ww  w  .j  a  v  a  2s  .co m
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}