Where to include truststore files in project

2019-04-17 14:58发布

问题:

I am trying to learn about SSL and have successfully made a client/server program that communicates over an SSL connection. I have generated my own truststore and keystore files that I would like my client and server programs to use. So far I am able to run both programs with through the command line using the following commands:

java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 ServerMain.java 

and

java -Djavax.net.ssl.trustStore=mySrvKeystore -Djavax.net.ssl.trustStorePassword=123456 Client.java

However, I would like to know if there is a possible way to implement the files into my project somehow so that in the future when I build it into a .jar file, I can bundle the files with it. Previously, I had done something similar with images by storing them in a res folder which is in my project folder and used "/res/image.jpg" as a path and it worked fine. I have tried the same method by using the System.setProperty("javax.net.ssl.trustStore", "/res/mySrvkeystore.jks") but it keeps returning file not found. Any help would be great! Thanks!

回答1:

  1. Include the keystore in your JAR file as a resource, as you did for your images.
  2. Access it via getResourceAsStream().
  3. Use that InputStream to load a KeyStore.
  4. Use the KeyStore to initialize a TrustManager.
  5. Use the TrustManager to initialize an SSLContext.
  6. Use the SSLContext to create your SSLSocketFactory.
  7. Use the SSLSocketFactory to create your SSLSocket.


标签: java ssl