當前位置: 首頁>>代碼示例>>Java>>正文


Java KeyManagerFactory.init方法代碼示例

本文整理匯總了Java中javax.net.ssl.KeyManagerFactory.init方法的典型用法代碼示例。如果您正苦於以下問題:Java KeyManagerFactory.init方法的具體用法?Java KeyManagerFactory.init怎麽用?Java KeyManagerFactory.init使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.net.ssl.KeyManagerFactory的用法示例。


在下文中一共展示了KeyManagerFactory.init方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getSSLServerSF

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
private SSLServerSocketFactory getSSLServerSF() throws Exception {

        char [] password =
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
        String keyFilename = System.getProperty("javax.net.ssl.keyStore");

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyFilename), password);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, password);

        KeyManager[] kms = kmf.getKeyManagers();
        TrustManager[] tms = new MyX509TM[] {new MyX509TM()};

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kms, tms, null);

        return ctx.getServerSocketFactory();
    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:EmptyCertificateAuthorities.java

示例2: createSslContext

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
private static SSLContext createSslContext(ApacheThriftClientConfig config)
{
    try {
        KeyStore trustStore = loadTrustStore(config.getTrustCertificate());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        KeyManager[] keyManagers = null;
        if (config.getKey() != null) {
            Optional<String> keyPassword = Optional.ofNullable(config.getKeyPassword());
            KeyStore keyStore = loadKeyStore(config.getTrustCertificate(), config.getKey(), keyPassword);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, new char[0]);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext;
    }
    catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException("Unable to load SSL keys", e);
    }
}
 
開發者ID:airlift,項目名稱:drift,代碼行數:25,代碼來源:ApacheThriftMethodInvokerFactory.java

示例3: makeSSLSocketFactory

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase
 */
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

        if (keystoreStream == null) {
            throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
        }

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);
        return makeSSLSocketFactory(keystore, keyManagerFactory);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
開發者ID:VideoDemo,項目名稱:M3U8_Video_demo,代碼行數:22,代碼來源:NanoHTTPD.java

示例4: prepareKeyManager

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {

        if (bksFile == null || password == null) {
            return null;
        }

        KeyStore clientKeyStore;
        try {
            clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
開發者ID:sundevin,項目名稱:rxjava2_retrofit2,代碼行數:19,代碼來源:CustomHttpsTrust.java

示例5: getSSLSocketFactory

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * 獲得SSLSocektFactory
 * 
 * @param password 密碼
 * @param keyStorePath 密鑰庫路徑
 * @param trustStorePath 信任庫路徑
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 實例化密鑰庫
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 獲得密鑰庫
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密鑰工廠
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 實例化信任庫
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 獲得信任庫
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任庫
	trustManagerFactory.init(trustStore);
	// 實例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 獲得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
開發者ID:tb544731152,項目名稱:iBase4J,代碼行數:33,代碼來源:HTTPSPKCSCoder.java

示例6: initChannel

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
@Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline pipeline = ch.pipeline();

     // SSL的安全鏈接
     if (ServerConfig.isSsl()) {
         SSLContext sslcontext = SSLContext.getInstance("TLS");
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         KeyStore ks = KeyStore.getInstance("JKS");
         String keyStorePath = ServerConfig.getKeyStorePath();
         String keyStorePassword = ServerConfig.getKeyStorePassword();
         ks.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
         String keyPassword = ServerConfig.getKeyPassword();
         kmf.init(ks, keyPassword.toCharArray());
         sslcontext.init(kmf.getKeyManagers(), null, null);
         SSLEngine sslEngine = sslcontext.createSSLEngine();
         sslEngine.setUseClientMode(false);
         sslEngine.setNeedClientAuth(false);
         /**
          * 務必放在第一位
          */
         pipeline.addLast(new SslHandler(sslEngine));
         logger.info("initChannel: addLast SslHandler");
         /**
          * Generates a temporary self-signed certificate for testing purposes.
          */
/*SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
//SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
if (sslCtx != null) {
	pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}*/
     }
     // Register HTTP handler chain.
     this.appendHttpPipeline(pipeline);
 }
 
開發者ID:geeker-lait,項目名稱:tasfe-framework,代碼行數:37,代碼來源:HttpChannelInitializer.java

示例7: getSSLContext

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * 獲取SSLContext
 * @param trustPasswd
 * @param keyPasswd
 * @return
 * @throws NoSuchAlgorithmException 
 * @throws KeyStoreException 
 * @throws IOException 
 * @throws CertificateException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 */
public static SSLContext getSSLContext(
		FileInputStream trustFileInputStream, String trustPasswd,
		FileInputStream keyFileInputStream, String keyPasswd)
		throws NoSuchAlgorithmException, KeyStoreException,
		CertificateException, IOException, UnrecoverableKeyException,
		KeyManagementException {

	// ca
	TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
	KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
	trustKeyStore.load(trustFileInputStream, HttpClientUtil
			.str2CharArray(trustPasswd));
	tmf.init(trustKeyStore);

	final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
	KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
	ks.load(keyFileInputStream, kp);
	kmf.init(ks, kp);

	SecureRandom rand = new SecureRandom();
	SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
	ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);

	return ctx;
}
 
開發者ID:jmdhappy,項目名稱:xxpay-master,代碼行數:39,代碼來源:HttpClientUtil.java

示例8: getKeyManager

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/** Devuelve un KeyManager a utilizar cuando se desea deshabilitar las comprobaciones de certificados en las conexiones SSL.
 * @return KeyManager[] Se genera un KeyManager[] utilizando el keystore almacenado en las propiedades del sistema.
 * @throws KeyStoreException Si no se puede cargar el KeyStore SSL.
 * @throws NoSuchAlgorithmException Si el JRE no soporta alg&uacute;n algoritmo necesario.
 * @throws CertificateException Si los certificados del KeyStore SSL son inv&aacute;lidos.
 * @throws IOException Si hay errores en la carga del fichero KeyStore SSL.
 * @throws UnrecoverableKeyException Si una clave del KeyStore SSL es inv&aacute;lida.
 * @throws NoSuchProviderException Si ocurre un error al recuperar la instancia del KeyStore. */
private static KeyManager[] getKeyManager() throws KeyStoreException,
                                                   NoSuchAlgorithmException,
                                                   CertificateException,
                                                   IOException,
                                                   UnrecoverableKeyException,
                                                   NoSuchProviderException {
	final String keyStore = System.getProperty(KEYSTORE);
	final String keyStorePassword = System.getProperty(KEYSTORE_PASS);
	final String keyStoreType = System.getProperty(KEYSTORE_TYPE);
	if (keyStore == null || keyStore.isEmpty()) {
		return null;
	}
	final File f = new File(keyStore);
	if (!f.isFile() || !f.canRead()) {
		LOGGER.warning("El KeyStore SSL no existe o no es legible: " + f.getAbsolutePath()); //$NON-NLS-1$
		return null;
	}
	final KeyStore keystore = KeyStore.getInstance(
		keyStoreType != null && !keyStoreType.isEmpty() ? keyStoreType : KEYSTORE_DEFAULT_TYPE
	);
	final InputStream fis = new FileInputStream(f);
	keystore.load(
		fis,
		keyStorePassword != null ? keyStorePassword.toCharArray() : null
	);
	fis.close();
	final KeyManagerFactory keyFac = KeyManagerFactory.getInstance(KEYMANAGER_INSTANCE);
	keyFac.init(
		keystore,
		keyStorePassword != null ? keyStorePassword.toCharArray() : null
	);
	return keyFac.getKeyManagers();
}
 
開發者ID:MiFirma,項目名稱:mi-firma-android,代碼行數:42,代碼來源:UrlHttpManagerImpl.java

示例9: trustManagerForCertificates

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
開發者ID:Shelmanxie,項目名稱:okhttpUtil,代碼行數:52,代碼來源:CustomTrustParams.java

示例10: setSSLContext

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
 * well as the password protecting the keystores/truststores.
 * 
 * @param keyStorePath The relative path and filename for the keystore
 * @param trustStorePath The relative path and filename for the truststore
 * @param keyStorePassword The password protecting the keystore
 */
public static void setSSLContext(
		String keyStorePath, 
		String trustStorePath,
		String keyStorePassword) {
    KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
    KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);

	try {
		// Initialize a key manager factory with the keystore
	    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyFactory.init(keyStore, keyStorePassword.toCharArray());
	    KeyManager[] keyManagers = keyFactory.getKeyManagers();

	    // Initialize a trust manager factory with the truststore
	    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
	    trustFactory.init(trustStore);
	    TrustManager[] trustManagers = trustFactory.getTrustManagers();

	    // Initialize an SSL context to use these managers and set as default
	    SSLContext sslContext = SSLContext.getInstance("TLS");
	    sslContext.init(keyManagers, trustManagers, null);
	    SSLContext.setDefault(sslContext); 
	} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | 
			KeyManagementException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
	}    
}
 
開發者ID:V2GClarity,項目名稱:RISE-V2G,代碼行數:36,代碼來源:SecurityUtils.java

示例11: prepareKeyManager

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {

    }
    return null;
}
 
開發者ID:qiaodashaoye,項目名稱:SuperHttp,代碼行數:14,代碼來源:HttpsUtils.java

示例12: getSslHandler

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:37,代碼來源:MqttSslHandlerProvider.java

示例13: prepareKeyManager

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        Log.e(e,"Https#prepareKeyManager error");
    }
    return null;
}
 
開發者ID:wzx54321,項目名稱:XinFramework,代碼行數:14,代碼來源:HttpsUtils.java

示例14: getContext

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
/**
 * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and
 * sets up keys.
 *
 * @return - SSLContext with a protocol specified by
 *           TESTED_SECURITY_PROTOCOL.
 */
public static SSLContext getContext() {
    try {
        java.security.Security.setProperty(
                "jdk.tls.disabledAlgorithms", "");
        java.security.Security.setProperty(
                "jdk.certpath.disabledAlgorithms", "");
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        char[] passphrase = PASSWD.toCharArray();
        try (FileInputStream keyFileStream =
                new FileInputStream(KEY_FILE_NAME)) {
            ks.load(keyFileStream, passphrase);
        }
        try (FileInputStream trustFileStream =
                new FileInputStream(TRUST_FILE_NAME)) {
            ts.load(trustFileStream, passphrase);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);
        SSLContext sslCtx =
                SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslCtx;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException |
            CertificateException | UnrecoverableKeyException |
            KeyManagementException ex) {
        throw new Error("Unexpected exception", ex);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:40,代碼來源:SSLEngineTestCase.java

示例15: createKeyManagers

import javax.net.ssl.KeyManagerFactory; //導入方法依賴的package包/類
public static KeyManager[] createKeyManagers(String clientCertificate) throws GeneralSecurityException, IOException {
    final KeyStore clientKs = createKeyStore("amq-client", clientCertificate);

    // create Key Manager
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("PKIX");
    kmFactory.init(clientKs, null);
    return kmFactory.getKeyManagers();
}
 
開發者ID:syndesisio,項目名稱:syndesis,代碼行數:9,代碼來源:ActiveMQUtil.java


注:本文中的javax.net.ssl.KeyManagerFactory.init方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。