https
HTTPS是以安全为目标的http通道,在http的基础上添加了ssl,传输加密和身份认证保证了传输过程的安全性,
https安全基础就是ssl,因此加密的详细内容就需要ssl
系统提供了身份验证,官方使用在万维网上的安全通讯。
1、生成证书
keytool -genkeypair -alias "java2021" -keyalg "RSA" -keysize 2048 -keystore "G:\zs\tomcat.keystore"
//上述解释
-alias 别名
-keypass 指定生成密钥的密码
-keyalg 指定密钥使用的加密算法(如 RSA)
-keysize 密钥大小
-validity 过期时间,单位天
-keystore 指定存储密钥的密钥库的生成路径、名称
-storepass 指定访问密钥库的密码
通过此命令运行,则CMD命令窗口会提示输入密钥库口令:654321
生成完成后
2.1.1配置tomcat方式
在tomcat的conf中的server.xml中配置
<Connector SSLEnabled="true" keystoreFile="G:\zs\tomcat.keystore" keystorePass="654321" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol">
</Connector>
保存运行
2.1.2访问地址
https://localhost:8443 即可
2.2.1Springboot的方式
2.2.2生成的tomcat.keystore放在resources里面
application.properties 或 application.yml 配置文件中配置相关https内容
server.port=8443
# 开启https
server.ssl.enabled=true
#配置跟证书对应
server.ssl.key-store=classpath:tomcat.keystore
# server.ssl.key-store-type=JKS
server.ssl.key-store-type=JKS
# 密码
server.ssl.key-store-password=654321
# springboot2.x不需要配置
server.ssl.key-password=654321
# 别名
server.ssl.key-alias=java2021
2.2.3配置协议跳转https
启动类main方法下面加上
// SpringBoot2.x配置HTTPS,并实现HTTP访问自动转向HTTPS
@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(httpConnector());
return tomcat;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080); // 监听Http的端口 端口号让占用就修改8080这个端口
connector.setSecure(false);
connector.setRedirectPort(8443); // 监听Http端口后转向Https端口
return connector;
}