Java Code Examples for java.security.KeyStore#getDefaultType()

The following examples show how to use java.security.KeyStore#getDefaultType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyStoreUtil.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and initializes an empty KeyStore using the specified keyStoreType.
 *
 * @param keyStoreType type of key store to initialize, or null to use the system default
 * @param provider     JCA provider to use, or null to use the system default
 * @return a new KeyStore
 */
public static KeyStore createEmptyKeyStore(String keyStoreType, String provider) {
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }

    KeyStore keyStore;
    try {
        if (provider == null) {
            keyStore = KeyStore.getInstance(keyStoreType);
        } else {
            keyStore = KeyStore.getInstance(keyStoreType, provider);
        }
        keyStore.load(null, null);
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | IOException e) {
        throw new KeyStoreAccessException("Error creating or initializing new KeyStore of type: " + keyStoreType, e);
    }
    return keyStore;
}
 
Example 2
Source File: ALiyunIotX509TrustManager.java    From rpi with Apache License 2.0 6 votes vote down vote up
public ALiyunIotX509TrustManager() throws Exception{
         //CA根证书,可以从官网下载
         InputStream in = BaseApplication.context.getAssets().open("root.crt");
//         InputStream in = SimpleClient4IOT.class.getResourceAsStream("/root.crt");
         CertificateFactory cf = CertificateFactory.getInstance("X.509");
         Certificate ca = null;
         try {
             ca = cf.generateCertificate(in);
         } catch (CertificateException e) {
            throw e;
         } finally {
             in.close();
         }
         String keyStoreType = KeyStore.getDefaultType();
         KeyStore keyStore = KeyStore.getInstance(keyStoreType);
         keyStore.load(null, null);
         keyStore.setCertificateEntry("ca", ca);
         String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
         TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
         tmf.init(keyStore);
         
         rootTrusm = (X509TrustManager) tmf.getTrustManagers()[0];
    
    }
 
Example 3
Source File: TrustManagers.java    From cwac-security with Apache License 2.0 6 votes vote down vote up
public static TrustManager[] useTrustStore(InputStream in,
                                           char[] password,
                                           String format)
                                                         throws GeneralSecurityException,
                                                         IOException,
                                                         NullPointerException {
  if (format == null) {
    format=KeyStore.getDefaultType();
  }

  KeyStore store=KeyStore.getInstance(format);

  try {
    store.load(in, password);
  }
  finally {
    in.close();
  }

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

  tmf.init(store);

  return(tmf.getTrustManagers());
}
 
Example 4
Source File: KeyStoreUtil.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Creates and initializes an empty KeyStore using the specified keyStoreType.
 *
 * @param keyStoreType type of key store to initialize, or null to use the system default
 * @param provider     JCA provider to use, or null to use the system default
 * @return a new KeyStore
 */
public static KeyStore createEmptyKeyStore(String keyStoreType, String provider) {
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }

    KeyStore keyStore;
    try {
        if (provider == null) {
            keyStore = KeyStore.getInstance(keyStoreType);
        } else {
            keyStore = KeyStore.getInstance(keyStoreType, provider);
        }
        keyStore.load(null, null);
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | IOException e) {
        throw new KeyStoreAccessException("Error creating or initializing new KeyStore of type: " + keyStoreType, e);
    }
    return keyStore;
}
 
Example 5
Source File: SslUtils.java    From ssl-utils-android with MIT License 6 votes vote down vote up
private static KeyStore getKeyStore(Context context, String fileName) {
    KeyStore keyStore = null;
    try {
        AssetManager assetManager = context.getAssets();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = assetManager.open(fileName);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
            Log.d("SslUtilsAndroid", "ca=" + ((X509Certificate) ca).getSubjectDN());
        } finally {
            caInput.close();
        }

        String keyStoreType = KeyStore.getDefaultType();
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        Log.e("SslUtilsAndroid","Error during getting keystore", e);
    }
    return keyStore;
}
 
Example 6
Source File: KeyStoreUtil.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
/**
 * Creates and initializes an empty KeyStore using the specified keyStoreType.
 *
 * @param keyStoreType type of key store to initialize, or null to use the system default
 * @param provider     JCA provider to use, or null to use the system default
 * @return a new KeyStore
 */
public static KeyStore createEmptyKeyStore(String keyStoreType, String provider) {
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }

    KeyStore keyStore;
    try {
        if (provider == null) {
            keyStore = KeyStore.getInstance(keyStoreType);
        } else {
            keyStore = KeyStore.getInstance(keyStoreType, provider);
        }
        keyStore.load(null, null);
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | IOException e) {
        throw new KeyStoreAccessException("Error creating or initializing new KeyStore of type: " + keyStoreType, e);
    }
    return keyStore;
}
 
Example 7
Source File: TLSUtilities.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
/**
 * Takes a given certificate and stores it inside the device's keystore.
 *
 * @param certificateStream the {@link InputStream} pointing to the certificate
 * @return a {@link ETSTLSTrust} containing the {@link X509TrustManager} as well as the {@link SSLContext} required for further usage.
 */
public static ETSTLSTrust createETSCertificateTrust(InputStream certificateStream) {

    try (InputStream caInput = new BufferedInputStream(certificateStream)) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca = cf.generateCertificate(caInput);

        // Create a KeyStore containing ÉTS's CA
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        Certificate storedCertificate = keyStore.getCertificate("ca");

        // Add the certificate to the keystore if it doesn't exists or replace it if it has been changed.
        if (!keyStore.containsAlias("ca") || storedCertificate != null && !ca.equals(storedCertificate)) {
            keyStore.setCertificateEntry("ca", ca);
        }

        // Create a TrustManager that trusts the CA in the KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses the TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        X509TrustManager trustManager =  (X509TrustManager) tmf.getTrustManagers()[0];
        ETSTLSTrust sslTrust = new ETSTLSTrust(trustManager, context);

        return sslTrust;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Source File: PinnedHttpClientBuilder.java    From extract with MIT License 5 votes vote down vote up
public static KeyStore createTrustStore(final String trustStorePath, final String trustStorePassword)
	throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {

	final String trustStoreExtension = FilenameUtils.getExtension(trustStorePath).toUpperCase(Locale.ROOT);
	final String trustStoreType;

	// Key store types are defined in Oracle's Cryptography Standard Algorithm Name Documentation:
	// http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyStore
	if (trustStoreExtension.equals("P12")) {
		trustStoreType = "PKCS12";
	} else {
		trustStoreType = KeyStore.getDefaultType();
	}

	final KeyStore trustStore = KeyStore.getInstance(trustStoreType);

	try (
		final InputStream input = new BufferedInputStream(new FileInputStream(trustStorePath))
	) {
		if (trustStoreExtension.equals("PEM") || trustStoreExtension.equals("DER")) {
			final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
				.generateCertificate(input);

			// Create an empty key store.
			// This operation should never throw an exception.
			trustStore.load(null, null);
			trustStore.setCertificateEntry(Integer.toString(1), certificate);
		} else {
			trustStore.load(input, trustStorePassword.toCharArray());
		}
	}

	return trustStore;
}
 
Example 9
Source File: LdapClientTrustStoreManager.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor used by connection configuration utility to load trust store manager.
 *
 * @param trustStoreFile    contains name of trust store file.
 * @param trustStorePw      contains the password for trust store
 * @param trustStoreFormat  contains the format for trust store
 * @param isExamineValidity boolean var determines if certificate will be examined for valid dates on load.
 */
public LdapClientTrustStoreManager( String trustStoreFile, char[] trustStorePw,
    String trustStoreFormat, boolean isExamineValidity )
{
    if ( trustStoreFile == null )
    {
        // Cannot continue, throw an unchecked exception:
        throw new RuntimeException( I18n.err( I18n.ERR_04174_INPUT_FILE_NAME_NULL ) );
    }
    
    // contains the file name of a valid JSSE TrustStore found on classpath:
    this.trustStoreFile = trustStoreFile;
    
    // the password to the JSSE TrustStore:
    this.trustStorePw = trustStorePw.clone();
    
    // If true, verify the current date is within the validity period for every certificate in the TrustStore:
    this.isExamineValidityDates = isExamineValidity;
    
    if ( trustStoreFormat == null )
    {
        this.trustStoreFormat = KeyStore.getDefaultType();
    }
    else
    {
        this.trustStoreFormat = trustStoreFormat;
    }
}
 
Example 10
Source File: HttpsUtils.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Build SSLSocketFactory using certificate file from assets.
 *
 * @param context
 * @param certFilePath
 * @return
 */
public static SSLSocketFactory getSSLSocketFactory(Context context, String certFilePath) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream is = context.getResources().getAssets().open(certFilePath);
    InputStream caInput = new BufferedInputStream(is);
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
        // System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext contexts = SSLContext.getInstance("TLS");
    contexts.init(null, tmf.getTrustManagers(), null);
    return contexts.getSocketFactory();


}
 
Example 11
Source File: Util.java    From ecosys with Apache License 2.0 5 votes vote down vote up
/**
 * load the CA and use it in the https connection
 * @param filename the CA filename
 * @return the SSL context
 */
public static SSLContext getSSLContext(String filename) throws Exception {
  try {
    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    // X.509 is a standard that defines the format of public key certificates, used in TLS/SSL.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(new FileInputStream(filename));
    Certificate ca = cf.generateCertificate(caInput);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
  } catch (Exception e) {
    throw new Exception("Failed to load the CA file: " + e.getMessage(), e);
  }
}
 
Example 12
Source File: Util.java    From ecosys with Apache License 2.0 5 votes vote down vote up
/**
 * load the CA and use it in the https connection
 * @param filename the CA filename
 * @return the SSL context
 */
public static SSLContext getSSLContext(String filename) throws Exception {
  try {
    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    // X.509 is a standard that defines the format of public key certificates, used in TLS/SSL.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(new FileInputStream(filename));
    Certificate ca = cf.generateCertificate(caInput);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
  } catch (Exception e) {
    throw new Exception("Failed to load the CA file: " + e.getMessage(), e);
  }
}
 
Example 13
Source File: Util.java    From ecosys with Apache License 2.0 5 votes vote down vote up
/**
 * load the CA and use it in the https connection
 * @param filename the CA filename
 * @return the SSL context
 */
public static SSLContext getSSLContext(String filename) throws Exception {
  try {
    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    // X.509 is a standard that defines the format of public key certificates, used in TLS/SSL.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = new BufferedInputStream(new FileInputStream(filename));
    Certificate ca = cf.generateCertificate(caInput);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
  } catch (Exception e) {
    throw new Exception("Failed to load the CA file: " + e.getMessage(), e);
  }
}
 
Example 14
Source File: Sentinel2ImageryProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
/** Load CAs from a custom certs file. */
protected static boolean applyCustomCertsFile(
    final HttpsURLConnection connection,
    final File customCertsFile) throws GeneralSecurityException, IOException {
  if (customCertsFile.exists()) {
    try {
      // Load CAs from an InputStream
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");

      final InputStream caInput = new BufferedInputStream(new FileInputStream(customCertsFile));
      final Certificate ca = cf.generateCertificate(caInput);

      // Create a KeyStore containing our trusted CAs
      final String keyStoreType = KeyStore.getDefaultType();
      final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);

      // Create a TrustManager that trusts the CAs in our KeyStore
      final String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      final TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(keyStore);

      // Create an SSLContext that uses our TrustManager
      final SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);
      connection.setSSLSocketFactory(context.getSocketFactory());

      return true;
    } catch (final GeneralSecurityException securityException) {
      LOGGER.error(
          "Unable to use keystore '" + customCertsFile.getAbsolutePath() + "'",
          securityException);
      throw securityException;
    }
  }
  return false;
}
 
Example 15
Source File: Main.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Load the srckeystore from a stream, used in -importkeystore
 * @return the src KeyStore
 */
KeyStore loadSourceKeyStore() throws Exception {

    InputStream is = null;
    File srcksfile = null;
    boolean srcIsPasswordless = false;

    if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||
            KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        if (!NONE.equals(srcksfname)) {
            System.err.println(MessageFormat.format(rb.getString
                (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype));
            System.err.println();
            tinyHelp();
        }
    } else {
        srcksfile = new File(srcksfname);
        is = new FileInputStream(srcksfile);
    }

    KeyStore store;
    try {
        // Probe for keystore type when filename is available
        if (srcksfile != null && is != null && srcProviderName == null &&
                srcstoretype == null) {
            store = KeyStore.getInstance(srcksfile, srcstorePass);
            srcstoretype = store.getType();
            if (srcstoretype.equalsIgnoreCase("pkcs12")) {
                srcIsPasswordless = PKCS12KeyStore.isPasswordless(srcksfile);
            }
        } else {
            if (srcstoretype == null) {
                srcstoretype = KeyStore.getDefaultType();
            }
            if (srcProviderName == null) {
                store = KeyStore.getInstance(srcstoretype);
            } else {
                store = KeyStore.getInstance(srcstoretype, srcProviderName);
            }
        }

        if (srcstorePass == null
                && !srcprotectedPath
                && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)
                && !srcIsPasswordless) {
            System.err.print(rb.getString("Enter.source.keystore.password."));
            System.err.flush();
            srcstorePass = Password.readPassword(System.in);
            passwords.add(srcstorePass);
        }

        // always let keypass be storepass when using pkcs12
        if (P12KEYSTORE.equalsIgnoreCase(srcstoretype)) {
            if (srckeyPass != null && srcstorePass != null &&
                    !Arrays.equals(srcstorePass, srckeyPass)) {
                MessageFormat form = new MessageFormat(rb.getString(
                    "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));
                Object[] source = {"-srckeypass"};
                System.err.println(form.format(source));
                srckeyPass = srcstorePass;
            }
        }

        store.load(is, srcstorePass);   // "is" already null in PKCS11
    } finally {
        if (is != null) {
            is.close();
        }
    }

    if (srcstorePass == null
            && !srcIsPasswordless
            && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        // anti refactoring, copied from printNoIntegrityWarning(),
        // but change 2 lines
        System.err.println();
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println(rb.getString
            (".The.integrity.of.the.information.stored.in.the.srckeystore."));
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println();
    }

    return store;
}
 
Example 16
Source File: StatisticManager.java    From Rumble with GNU General Public License v3.0 4 votes vote down vote up
public void onEventAsync(LinkLayerStarted event) {
    if(!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;

    if(RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if(!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(RumbleApplication.getContext()
                    .getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

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

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

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex)
        {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}
 
Example 17
Source File: Main.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Load the srckeystore from a stream, used in -importkeystore
 * @returns the src KeyStore
 */
KeyStore loadSourceKeyStore() throws Exception {

    InputStream is = null;
    File srcksfile = null;

    if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||
            KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        if (!NONE.equals(srcksfname)) {
            System.err.println(MessageFormat.format(rb.getString
                (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype));
            System.err.println();
            tinyHelp();
        }
    } else {
        srcksfile = new File(srcksfname);
            is = new FileInputStream(srcksfile);
    }

    KeyStore store;
    try {
        if (srcstoretype == null) {
            srcstoretype = KeyStore.getDefaultType();
        }
        if (srcProviderName == null) {
            store = KeyStore.getInstance(srcstoretype);
        } else {
            store = KeyStore.getInstance(srcstoretype, srcProviderName);
        }

        if (srcstorePass == null
                && !srcprotectedPath
                && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
            System.err.print(rb.getString("Enter.source.keystore.password."));
            System.err.flush();
            srcstorePass = Password.readPassword(System.in);
            passwords.add(srcstorePass);
        }

        // always let keypass be storepass when using pkcs12
        if (P12KEYSTORE.equalsIgnoreCase(srcstoretype)) {
            if (srckeyPass != null && srcstorePass != null &&
                    !Arrays.equals(srcstorePass, srckeyPass)) {
                MessageFormat form = new MessageFormat(rb.getString(
                    "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));
                Object[] source = {"-srckeypass"};
                System.err.println(form.format(source));
                srckeyPass = srcstorePass;
            }
        }

        store.load(is, srcstorePass);   // "is" already null in PKCS11
    } finally {
        if (is != null) {
            is.close();
        }
    }

    if (srcstorePass == null
            && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        // anti refactoring, copied from printNoIntegrityWarning(),
        // but change 2 lines
        System.err.println();
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println(rb.getString
            (".The.integrity.of.the.information.stored.in.the.srckeystore."));
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println();
    }

    return store;
}
 
Example 18
Source File: Main.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Load the srckeystore from a stream, used in -importkeystore
 * @returns the src KeyStore
 */
KeyStore loadSourceKeyStore() throws Exception {

    InputStream is = null;
    File srcksfile = null;

    if (P11KEYSTORE.equalsIgnoreCase(srcstoretype) ||
            KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        if (!NONE.equals(srcksfname)) {
            System.err.println(MessageFormat.format(rb.getString
                (".keystore.must.be.NONE.if.storetype.is.{0}"), srcstoretype));
            System.err.println();
            tinyHelp();
        }
    } else {
        srcksfile = new File(srcksfname);
            is = new FileInputStream(srcksfile);
    }

    KeyStore store;
    try {
        if (srcstoretype == null) {
            srcstoretype = KeyStore.getDefaultType();
        }
        if (srcProviderName == null) {
            store = KeyStore.getInstance(srcstoretype);
        } else {
            store = KeyStore.getInstance(srcstoretype, srcProviderName);
        }

        if (srcstorePass == null
                && !srcprotectedPath
                && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
            System.err.print(rb.getString("Enter.source.keystore.password."));
            System.err.flush();
            srcstorePass = Password.readPassword(System.in);
            passwords.add(srcstorePass);
        }

        // always let keypass be storepass when using pkcs12
        if (P12KEYSTORE.equalsIgnoreCase(srcstoretype)) {
            if (srckeyPass != null && srcstorePass != null &&
                    !Arrays.equals(srcstorePass, srckeyPass)) {
                MessageFormat form = new MessageFormat(rb.getString(
                    "Warning.Different.store.and.key.passwords.not.supported.for.PKCS12.KeyStores.Ignoring.user.specified.command.value."));
                Object[] source = {"-srckeypass"};
                System.err.println(form.format(source));
                srckeyPass = srcstorePass;
            }
        }

        store.load(is, srcstorePass);   // "is" already null in PKCS11
    } finally {
        if (is != null) {
            is.close();
        }
    }

    if (srcstorePass == null
            && !KeyStoreUtil.isWindowsKeyStore(srcstoretype)) {
        // anti refactoring, copied from printNoIntegrityWarning(),
        // but change 2 lines
        System.err.println();
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println(rb.getString
            (".The.integrity.of.the.information.stored.in.the.srckeystore."));
        System.err.println(rb.getString
            (".WARNING.WARNING.WARNING."));
        System.err.println();
    }

    return store;
}
 
Example 19
Source File: JdkSslFactory.java    From ambry with Apache License 2.0 4 votes vote down vote up
private SecurityStore(String type, String path, String password) {
  this.type = type == null ? KeyStore.getDefaultType() : type;
  this.path = path;
  this.password = password;
}
 
Example 20
Source File: FileTrustStoreSslSocketFactory.java    From springboot-shiro-cas-mybatis with MIT License 2 votes vote down vote up
/**
 * Instantiates a new trusted proxy authentication trust store ssl socket factory.
 * Defaults to <code>TLSv1</code> and {@link SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER}
 * for the supported protocols and hostname verification.
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 */
public FileTrustStoreSslSocketFactory(final File trustStoreFile, final String trustStorePassword) {
    this(trustStoreFile, trustStorePassword, KeyStore.getDefaultType());
}