Java Code Examples for java.security.KeyStore.getInstance()

The following are Jave code examples for showing how to use getInstance() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rebase-android   File: BlackBox.java   View Source Code Vote up 7 votes
/**
 * Creates a public and private key and stores it using the AndroidKeyStore,
 * so that only this application will be able to access the keys.
 */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.TEN)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
Example 2
Project: jdk8u-jdk   File: ClientHelloRead.java   View Source Code Vote up 6 votes
private static ServerSocketFactory getServerSocketFactory
               (boolean useSSL) throws Exception {
    if (useSSL) {
        SSLServerSocketFactory ssf = null;
        // set up key manager to do server authentication
        SSLContext ctx;
        KeyManagerFactory kmf;
        KeyStore ks;
        char[] passphrase = passwd.toCharArray();

        ctx = SSLContext.getInstance("TLS");
        kmf = KeyManagerFactory.getInstance("SunX509");
        ks = KeyStore.getInstance("JKS");

        ks.load(new FileInputStream(System.getProperty(
                    "javax.net.ssl.keyStore")), passphrase);
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, null);

        ssf = ctx.getServerSocketFactory();
        return ssf;
    } else {
        return ServerSocketFactory.getDefault();
    }
}
 
Example 3
Project: calcite-avatica   File: SslDriverTest.java   View Source Code Vote up 6 votes
private void createSelfSignedCert(File targetKeystore, String keyName,
    String keystorePassword) {
  if (targetKeystore.exists()) {
    throw new RuntimeException("Keystore already exists: " + targetKeystore);
  }

  try {
    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(),
        kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] {cert});
    try (FileOutputStream fos = new FileOutputStream(targetKeystore)) {
      keystore.store(fos, password);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Project: wx-idk   File: HttpsRequestTools.java   View Source Code Vote up 6 votes
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
Example 5
Project: dremio-oss   File: HttpsConnectorGenerator.java   View Source Code Vote up 6 votes
public KeyStore getTrustStore(DremioConfig config) throws GeneralSecurityException, IOException {
  String trustStorePath = getConfig(config, WEB_SSL_TRUSTSTORE);
  char[] trustStorePassword;
  if (trustStorePath == null) {
    // Check if auto-generated certificates are used
    Path path = Paths.get(config.getString(LOCAL_WRITE_PATH_STRING), TRUST_STORE_FILE);
    if (Files.notExists(path)) {
      return null;
    }

    trustStorePath = path.toString();
    trustStorePassword = UNSECURE_PASSWORD_CHARARRAY;
  } else {
    logger.info("Loading configured truststore at {}", trustStorePath);
    String password = getConfig(config, WEB_SSL_TRUSTSTORE_PASSWORD);
    trustStorePassword = password != null ? password.toCharArray() : null;
  }

  KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  try(InputStream stream = Files.newInputStream(Paths.get(trustStorePath))) {
    trustStore.load(stream, trustStorePassword);
  }
  return trustStore;
}
 
Example 6
Project: ats-framework   File: SMimePackageEncryptor.java   View Source Code Vote up 6 votes
private KeyStore getKeystore() throws ActionException {

        KeyStore ks = null;
        try (FileInputStream fis = new FileInputStream(certLocation)) {
            ks = KeyStore.getInstance(PKCS12_KEYSTORE_TYPE, BouncyCastleProvider.PROVIDER_NAME);
            ks.load(fis, certPassword.toCharArray());

            if (aliasOrCN == null) {
                Enumeration<String> aliases = ks.aliases();
                String alias = aliases.nextElement();
                aliasOrCN = alias;
            }

        } catch (Exception e) {
            throw new ActionException(e);
        }
        return ks;
    }
 
Example 7
Project: NioSmtpClient   File: FakeTlsContext.java   View Source Code Vote up 5 votes
private static KeyManagerFactory getKeyManagerFactory() throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(getKeyStoreInputStream(), PASSWORD);

  KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
  kmf.init(ks, PASSWORD);

  return kmf;
}
 
Example 8
Project: an2linuxclient   File: TlsHelper.java   View Source Code Vote up 5 votes
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 9
Project: java-android-websocket-client   File: SSLContextBuilder.java   View Source Code Vote up 5 votes
public SSLContextBuilder loadTrustMaterial(
        final File file,
        final char[] storePassword,
        final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(file, "Truststore file");
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        trustStore.load(instream, storePassword);
    } finally {
        instream.close();
    }
    return loadTrustMaterial(trustStore, trustStrategy);
}
 
Example 10
Project: mDL-ILP   File: NetUtils.java   View Source Code Vote up 5 votes
public static void setUpSSL(Context context) {
        // set up keystore
        try (InputStream clientInput = context.getResources().openRawResource(R.raw.rdw_poc_mdl_client_ca);
             //InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ca)) {
             InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ssl)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            //java.security.cert.Certificate clientCA = cf.generateCertificate(clientInput);

            // This part sends my cert to server
//            KeyStore clientStore = KeyStore.getInstance("PKCS12");
//            clientStore.load(clientInput, "password".toCharArray());
            //clientStore.setCertificateEntry("", clientCA);

//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            keyManagerFactory.init(clientStore, null);

            // this part trusts a remote certificate
            java.security.cert.Certificate serverCA = cf.generateCertificate(serverInput);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore serverStore = KeyStore.getInstance("PKCS12");
            serverStore.load(null, null);
            serverStore.setCertificateEntry("", serverCA);
            tmf.init(serverStore);

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

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        } catch (Exception e) {
            Log.e("TLS", "Something went wrong", e);
        }
    }
 
Example 11
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   View Source Code Vote up 5 votes
private KeyManager[] getKeyManagers() {
    if (keystoreFilename != null && keystorePassword != null && keystoreType != null) {
        try {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(keystoreType);
            loadKeystore(keystore, keystoreFilename, keystorePassword);
            keyManagerFactory.init(keystore, keystorePassword.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to load Keystore", e);
        }
    } else {
        return null;
    }
}
 
Example 12
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile     the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType     the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword,
                                               final String trustStoreType) {
    try {

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (InputStream casStream = trustStoreFile.getInputStream()) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useProtocol("SSL").build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
 
Example 13
Project: trust-wallet-android   File: KS.java   View Source Code Vote up 5 votes
private synchronized static void removeAliasAndFiles(Context context, String alias, String dataFileName, String ivFileName) {
	KeyStore keyStore;
	try {
		keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
		keyStore.load(null);
		keyStore.deleteEntry(alias);
		new File(getFilePath(context, dataFileName)).delete();
		new File(getFilePath(context, ivFileName)).delete();
	} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
		e.printStackTrace();
	}
}
 
Example 14
Project: jdk8u-jdk   File: TestJKSWithSecretKey.java   View Source Code Vote up 5 votes
public static void main (String[] args) throws Exception {
    SecretKey key = new SecretKeySpec(new byte[8], "DES");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, passwd);

    try {
        // store the SecretKey
        ks.setKeyEntry("test_encrypt_key", key, passwd, null);
        throw new Exception("Should throw KeyStoreException when " +
            "storing SecretKey into JKS keystores");
    } catch (KeyStoreException kse) {
        // expected exception thrown; swallow
    }
}
 
Example 15
Project: mapbook-android   File: CredentialCryptographer.java   View Source Code Vote up 4 votes
/**
 * Decrypt contents of File given path and
 * return a string representation of the decrypted data
 * @param encryptedDataFileName String representing file name
 * @return Decrypted string or null if decryption fails
 * @throws Exception related to decryption
 */
private String decryptData (final String encryptedDataFileName) throws Exception{
  String decryptedString;

  final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
  keyStore.load(null);
  final SecretKey key = (SecretKey) keyStore.getKey(ALIAS, null);

  final Cipher c = Cipher.getInstance(CIPHER_TYPE);

  final File file = new File(getFilePath(encryptedDataFileName));
  final int fileSize = (int)file.length();

  // Need to provide the GCMSpec used by the
  // encryption method when decrypting
  final File ivFile = new File(getFilePath(Constants.IV_FILE));
  final int ivFileSize =  (int) ivFile.length();
  final FileInputStream fis = new FileInputStream(getFilePath(Constants.IV_FILE));
  final byte [] iv = new byte[ivFileSize];

  int index = 0;
  int nextByte;
  while ((nextByte = fis.read()) != -1){
    iv[index] = (byte) nextByte;
    index++;
  }
  fis.close();

  GCMParameterSpec spec = new GCMParameterSpec(128, iv);
  Log.i(TAG, "Decrypted spec iv length " +  spec.getIV().length + " tag length = "+ spec.getTLen());
  c.init(Cipher.DECRYPT_MODE, key, spec);

   final CipherInputStream cipherInputStream =
      new CipherInputStream(new FileInputStream(getFilePath(encryptedDataFileName)),
          c);
  final byte[] fileContentBytes = new byte[fileSize];

  index = 0;
  while ((nextByte = cipherInputStream.read()) != -1) {
    fileContentBytes[index] = (byte) nextByte;
    index++;
  }
  cipherInputStream.close();

  decryptedString = new String(fileContentBytes, 0, index, Charsets.UTF_8);
  Log.v(TAG, "Decrypted string = " + decryptedString);

  return decryptedString;
}
 
Example 16
Project: letv   File: HttpUtils.java   View Source Code Vote up 4 votes
MyX509TrustManager() throws Exception {
    KeyStore instance;
    Throwable th;
    FileInputStream fileInputStream;
    try {
        instance = KeyStore.getInstance("JKS");
    } catch (Exception e) {
        instance = null;
    }
    TrustManager[] trustManagerArr = new TrustManager[0];
    if (instance != null) {
        try {
            InputStream fileInputStream2 = new FileInputStream("trustedCerts");
            try {
                instance.load(fileInputStream2, "passphrase".toCharArray());
                TrustManagerFactory instance2 = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
                instance2.init(instance);
                TrustManager[] trustManagers = instance2.getTrustManagers();
                if (fileInputStream2 != null) {
                    fileInputStream2.close();
                }
            } catch (Throwable th2) {
                th = th2;
                InputStream inputStream = fileInputStream2;
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                throw th;
            }
        } catch (Throwable th3) {
            Throwable th4 = th3;
            fileInputStream = null;
            th = th4;
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            throw th;
        }
    }
    TrustManagerFactory instance3 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    instance3.init((KeyStore) null);
    trustManagers = instance3.getTrustManagers();
    for (int i = 0; i < trustManagers.length; i++) {
        if (trustManagers[i] instanceof X509TrustManager) {
            this.a = (X509TrustManager) trustManagers[i];
            return;
        }
    }
    throw new Exception("Couldn't initialize");
}
 
Example 17
Project: openjdk-jdk10   File: TokenStore.java   View Source Code Vote up 4 votes
private static void init() throws Exception {

        // first write policy files

        PolicyParser pp = new PolicyParser();
        pp.read(new StringReader(POLICY_NO_STORE));
        pp.write(new FileWriter(NO_STORE_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL));
        pp.write(new FileWriter(URL_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T));
        pp.write(new FileWriter(URL_T_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T_P));
        pp.write(new FileWriter(URL_T_P_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_PWD));
        pp.write(new FileWriter(URL_PWD_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_URL_T_P_PWD));
        pp.write(new FileWriter(URL_T_P_PWD_FILE, false));

        pp = new PolicyParser();
        pp.read(new StringReader(POLICY_BADPASS));
        pp.write(new FileWriter(BADPASS_FILE, false));

        // next load keystore data to build PD's

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream
                        (System.getProperty("test.src", ".") +
                        File.separatorChar +
                        "TokenStore.keystore"),
                storePassword);

        NO_STORE_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"),
                            (java.security.cert.Certificate[]) null),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        Certificate[] chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL");
        URL_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL_T");
        URL_T_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals

        chain = (Certificate[])
                        ks.getCertificateChain("POLICY_URL_T_P");
        URL_T_P_DOMAIN = new ProtectionDomain
                        (new CodeSource(new URL("file:/foo"), chain),
                        null,  // perms
                        null,  // class loader
                        null);  // principals
    }
 
Example 18
Project: react-native-secure-key-store   File: RNSecureKeyStoreModule.java   View Source Code Vote up 4 votes
private PrivateKey getPrivateKey(String alias) throws GeneralSecurityException, IOException {
  KeyStore keyStore = KeyStore.getInstance(getKeyStore());
  keyStore.load(null);
  return (PrivateKey) keyStore.getKey(alias, null);
}
 
Example 19
Project: oscm   File: APPlatformServiceBeanIT.java   View Source Code Vote up 4 votes
@Test
public void testCheckToken() throws Exception {

    CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
    gen.generate(1024);
    X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"),
            new Date(), 10000000);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    String alias = "temp";
    String loc = "./temp.jks";
    String password = "changeit";
    ks.load(null, password.toCharArray());

    ks.setCertificateEntry(alias, cert);

    FileOutputStream fos = new FileOutputStream(loc);
    ks.store(fos, password.toCharArray());
    fos.close();

    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE)).thenReturn(loc);
    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE_PASSWORD))
            .thenReturn(password);
    Mockito.when(configSvc.getProxyConfigurationSetting(
            PlatformConfigurationKey.APP_TRUSTSTORE_BSS_ALIAS))
            .thenReturn(alias);

    String token = UUID.randomUUID().toString();

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(token.getBytes(StandardCharsets.UTF_8));
    byte[] tokenHash = md.digest();

    Key key = gen.getPrivateKey();
    Cipher c = Cipher.getInstance(key.getAlgorithm());
    c.init(Cipher.ENCRYPT_MODE, key);

    String tokenSignature = Base64
            .encodeBase64URLSafeString(c.doFinal(tokenHash));

    boolean check = platformSvc.checkToken(token, tokenSignature);

    assertTrue(check);

    Files.delete(new File(loc).toPath());
}
 
Example 20
Project: monarch   File: SocketCreator.java   View Source Code Vote up 4 votes
private KeyManager[] getKeyManagers() throws KeyStoreException, IOException,
    NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
  GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

  KeyManager[] keyManagers = null;
  String keyStoreType = sslConfig.getKeystoreType();
  if (StringUtils.isEmpty(keyStoreType)) {
    // read from console, default on empty
    if (consoleReader.isSupported()) {
      keyStoreType =
          consoleReader.readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
    } else {
      keyStoreType = KeyStore.getDefaultType();
    }
  }
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  String keyStoreFilePath = sslConfig.getKeystore();
  if (StringUtils.isEmpty(keyStoreFilePath)) {
    if (consoleReader.isSupported()) {
      keyStoreFilePath = consoleReader
          .readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
    } else {
      keyStoreFilePath =
          System.getProperty("user.home") + System.getProperty("file.separator") + ".keystore";
    }
  }

  FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
  String passwordString = sslConfig.getKeystorePassword();
  char[] password = null;
  if (passwordString != null) {
    if (passwordString.trim().equals("")) {
      String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
      if (!StringUtils.isEmpty(encryptedPass)) {
        String toDecrypt = "encrypted(" + encryptedPass + ")";
        passwordString = PasswordUtil.decrypt(toDecrypt);
        password = passwordString.toCharArray();
      }
      // read from the console
      if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
        password = consoleReader.readPassword(
            "Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
      }
    } else {
      password = passwordString.toCharArray();
    }
  }
  keyStore.load(fileInputStream, password);
  // default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
  // security properties
  KeyManagerFactory keyManagerFactory =
      KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  keyManagers = keyManagerFactory.getKeyManagers();
  // follow the security tip in java doc
  if (password != null) {
    java.util.Arrays.fill(password, ' ');
  }

  KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];

  for (int i = 0; i < keyManagers.length; i++)

  {
    extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
  }

  return extendedKeyManagers;
}