问题
I'm trying to understand what's going on in this code.
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", socketFactory, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
My Questions:
trustStore.load(instream, "nopassword".toCharArray());
is doing what exactly? From reading the documentation load()
will load KeyStore data from an input stream (which is just an empty file we just created), using some arbitrary "nopassword". Why not just load it with null
as the InputStream parameter and an empty string as the password field?
And then what is happening when this empty KeyStore is being passed to the SSLSocketFactory constructor? What's the result of such an operation?
Or -- is this simply an example where in a real application you would have to actually put a reference to an existing keystore file / password?
回答1:
Or -- is this simply an example where in a real application you would have to actually put a reference to an existing keystore file / password?
It really looks that way. There is no "my.keystore"
file distributed in either the binary or source distributions of HttpClient 4.0.1. For this to run you would create an actual keystore. You could use either keytool or Portecle.
This example is showing you how to utilize a different trust store than the one that the JVM uses by default ($JAVA_HOME/jre/lib/security/cacerts) for this instance of DefaultHttpClient
. This is useful when an SSL site is using a certificate signed by their own in-house certificate authority. The SSL connection will only be established when the signer of the server certificate is recognized. The Wikipedia entry on TLS is a decent introduction if you are unfamiliar with the concept.
回答2:
This example tries to show you how to load your own trust store. To get this example working, you need to have a file called "my.keystore" in your current directory and the password for the keystore is "nopassword".
Please note new File("my.keystore")
doesn't necessarily create a new file. It simply creates a File object pointing to the path.
来源:https://stackoverflow.com/questions/2741457/keystore-httpclient-and-https-can-someone-explain-this-code-to-me