1、访问本机,配置证书:
默认密钥:
changeit
生成证书:
keytool -genkey -alias mytomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore D:/keystore.p12 -validity 3650 -keypass 123456 -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" -storepass 123456
证书放入resources路径下:
yml配置:
ssl: key-store: classpath:keystore.p12 key-store-password: 123456 key-password: 123456 key-store-type: PKCS12 key-alias: mytomcat
https: port: 443
如果想http和https都能访问,还得来个配置类:
package com.dkt.web.core.config;
/*
*@ClassName t
*@Description TODO
*@Author wangchao
*@Date 2022/4/6 17:13
*@Version 1.0
*/
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Value("${https.port}")
private int httpsPort;
@Value("${server.port}")
private int serverPort;
@Value("${server.ssl.key-store}")
private String keystoreFile;
@Value("${server.ssl.key-store-type}")
private String keystoreType;
@Value("${server.ssl.key-store-password}")
private String keystorePass;
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
((TomcatServletWebServerFactory)factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector httpsconnector) {
httpsconnector.setPort(httpsPort);
httpsconnector.setSecure(true);
httpsconnector.setScheme("https");
Http11NioProtocol protocol = (Http11NioProtocol) httpsconnector.getProtocolHandler();
protocol.setMaxConnections(200);
protocol.setMaxThreads(200);
protocol.setSelectorTimeout(3000);
protocol.setSessionTimeout(3000);
protocol.setConnectionTimeout(3000);
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystoreFile);
protocol.setKeystorePass(keystorePass);
protocol.setKeystoreType(keystoreType);
//先构造一个http的tomcat服务再重定向到https
Connector httpconnector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
httpconnector.setPort(serverPort);
httpconnector.setScheme("http");
httpconnector.setSecure(false);
httpconnector.setRedirectPort(httpsPort);
((TomcatServletWebServerFactory)factory).addAdditionalTomcatConnectors(httpconnector);
}
});
}
}
这样OK;
2、如果是访问一个支付网站,对方是加密https的接口,这时候需要下载对方网站的证书,安装到jdk的路径里
2.1 访问该网站,url左边的锁-->连接是安全的-》证书有效-》详细信息-》复制到文件,比如1.cer
2.2keytool 命令导入到jdk密钥库;
keytool -import -alias ssodemo3 -file D:/2.cer -keystore "D:\Program Files\Java\jdk1.8.0_172\jre\lib\security\cacerts" -storepass changeit -trustcacerts
如此,访问该单独的https网站就可以了。