java.security.KeyStore#getDefaultType ( )源码实例Demo

下面列出了java.security.KeyStore#getDefaultType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: browserup-proxy   文件: KeyStoreUtil.java
/**
 * 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;
}
 
源代码2 项目: cwac-security   文件: TrustManagers.java
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());
}
 
源代码3 项目: CapturePacket   文件: KeyStoreUtil.java
/**
 * 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;
}
 
源代码4 项目: AndroidHttpCapture   文件: KeyStoreUtil.java
/**
 * 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;
}
 
源代码5 项目: ssl-utils-android   文件: SslUtils.java
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;
}
 
源代码6 项目: rpi   文件: ALiyunIotX509TrustManager.java
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];
    
    }
 
源代码7 项目: geowave   文件: Sentinel2ImageryProvider.java
/** 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;
}
 
源代码8 项目: ecosys   文件: Util.java
/**
 * 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);
  }
}
 
源代码9 项目: ecosys   文件: Util.java
/**
 * 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);
  }
}
 
源代码10 项目: ecosys   文件: Util.java
/**
 * 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);
  }
}
 
源代码11 项目: UltimateAndroid   文件: HttpsUtils.java
/**
 * 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();


}
 
/**
 * 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;
    }
}
 
源代码13 项目: extract   文件: PinnedHttpClientBuilder.java
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;
}
 
源代码14 项目: ETSMobile-Android2   文件: TLSUtilities.java
/**
 * 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;
}
 
源代码15 项目: ambry   文件: JdkSslFactory.java
private SecurityStore(String type, String path, String password) {
  this.type = type == null ? KeyStore.getDefaultType() : type;
  this.path = path;
  this.password = password;
}
 
源代码16 项目: dragonwell8_jdk   文件: Main.java
/**
 * 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;
}
 
源代码17 项目: Bytecoder   文件: Main.java
/**
 * 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;
}
 
源代码18 项目: Rumble   文件: StatisticManager.java
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());
        }
    }
}
 
源代码19 项目: openjdk-jdk8u-backup   文件: Main.java
/**
 * 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;
}
 
/**
 * 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());
}