创建了一个 https 服务器:
public void startHttpsServer() {
try {
httpsServer = com.sun.net.httpserver.HttpsServer.create();
httpsServer.bind(new InetSocketAddress(httpsPort), 5);
httpsServer.createContext("/getVersion", new VersionHandler());
httpsServer.createContext("/sysInfo", new SysInfoHandler());
httpsServer.createContext("/cashRegisterService", new CashRegisterHandler());
httpsServer.createContext("/printService", new PrintServiceHandler());
char[] storepass = "testtest".toCharArray();
char[] keypass = "testtest".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(HttpServer.class.getResourceAsStream("test.jks"), storepass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, keypass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(ssl) {
public void configure (HttpsParameters params) {
// get the remote address if needed
InetSocketAddress remote = params.getClientAddress();
SSLContext c = getSSLContext();
SSLParameters sslparams = c.getDefaultSSLParameters();
// get the default parameters
params.setSSLParameters(sslparams);
// statement above could throw IAE if any params invalid.
// eg. if app has a UI and parameters supplied by a user.
}
});
} catch (IOException e) {
e.printStackTrace();
Logger.addLogLine("HttpServerError",e.toString(), e);
} catch (CertificateException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) {
e.printStackTrace();
}
ExecutorService executor = Executors.newFixedThreadPool(5);
httpsServer.setExecutor(executor);
httpsServer.start();
try {
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
似乎仍然需要使用证书创建存储。完全的:
keytool -v -genkey -dname "CN=localhost, OU=Developers, O=NA, L=Kiev, C=UA" -alias parent -storetype jks -keystore test.jks -validity 365 -keyalg RSA -keysize 2048 -storepass testtest -keypass testtest
我启动我的服务并执行 curl:
curl -v -H -GET https://localhost:32910/sysInfo
结果:
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 32910 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:32910
* stopped the pause stream!
* Closing connection 0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to localhost:32910
我错过了什么或做错了什么?SSL有什么问题?
问题在于:
使用 /test.jks 示例正确指定:
test.jks 也应该在 /main/resources