How to use a file in a jar as javax.net.ssl.keystore?

后端 未结 3 791
渐次进展
渐次进展 2020-12-01 08:13

I\'m trying to do something like

URL clientks = com.messaging.SubscriptionManager.class.getResource( \"client.ks\" );
String path = clientks.toURI().getPath         


        
3条回答
  •  悲哀的现实
    2020-12-01 08:53

    Still working on implementation, but I believe it is possible to load the keystore from the jar via InputStream and explicitly set the TrustStore programatically (vs setting the System properties). See the article: Setting multiple truststore on the same JVM

    Got it working!

    InputStream keystoreInput = Thread.currentThread().getContextClassLoader()
        .getResourceAsStream(/client.ks");
    InputStream truststoreInput = Thread.currentThread().getContextClassLoader()
        .getResourceAsStream(/client.ts");
    setSSLFactories(keystoreInput, "password", truststoreInput);
    keystoreInput.close();
    truststoreInput.close();
    
    private static void setSSLFactories(InputStream keyStream, String keyStorePassword, 
        InputStream trustStream) throws Exception
    {    
      // Get keyStore
      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());    
    
      // if your store is password protected then declare it (it can be null however)
      char[] keyPassword = keyStorePassword.toCharArray();
    
      // load the stream to your store
      keyStore.load(keyStream, keyPassword);
    
      // initialize a key manager factory with the key store
      KeyManagerFactory keyFactory = 
      KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());    
      keyFactory.init(keyStore, keyPassword);
    
      // get the key managers from the factory
      KeyManager[] keyManagers = keyFactory.getKeyManagers();
    
      // Now get trustStore
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());    
    
      // if your store is password protected then declare it (it can be null however)
      //char[] trustPassword = password.toCharArray();
    
      // load the stream to your store
      trustStore.load(trustStream, null);
    
      // initialize a trust manager factory with the trusted store
      TrustManagerFactory trustFactory = 
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
      trustFactory.init(trustStore);
    
      // get the trust managers from the factory
      TrustManager[] trustManagers = trustFactory.getTrustManagers();
    
      // initialize an ssl context to use these managers and set as default
      SSLContext sslContext = SSLContext.getInstance("SSL");
      sslContext.init(keyManagers, trustManagers, null);
      SSLContext.setDefault(sslContext);    
    }
    

提交回复
热议问题