1.背景
主要原因是http便利高效的同时也带来了缺点。
1.通信使用的是明文(没有加密),内容可能会别人抓包截取获得。
2.不验证通信方的身份,因此有可能遭遇伪装。
3.无法证明报文的完整性,所以有可能已遭篡改。
2.原理
服务端证书模式
1.开始SSL握手协议,客户端发送SSL的版本号、加密组件(加密算法和秘钥长度)
2.服务端接受请求后,筛选出加密组件和SSL的版本号返回信息
3.服务端继续响应,发送公共秘钥证书
4.服务端最后发送helloDone,SSL握手协议结束。
5.客户端验证公共秘钥证书正确后取出公共秘钥,生成一个随机密码串作为共享密钥方式的密钥(当然了这个密钥已经用刚刚拿到的公共秘钥加密过了)
6.客户端接着发送请求说明接下来的信息都是加密信息
7.客户端发送finish报文,以服务器是否能正确解密判断握手是否成功
8.服务器同样重复步骤6和7进行响应
9.双方finish结束
10.SSL连接正式成功
11.开始http通信
12.客户端断开连接,发送close_notify报文结束。
3.内容
springboot+openssl模拟HTTPS
1.生成证书,可以使自签名或者从SSL证书授权中心获得的。
JDK中keytool是一个证书管理工具,可以生成自签名证书。
本人这里用的系统是deepin,然后生成命令如下(找不到keytoo命令的先去配置java环境)
我指定的名字叫liliguang.keystore 别名叫liliguang,密码自己设置,我这里用的tomcat,最后那个直接按得回车
keytool -genkey -alias liliguang -keyalg RSA -keystore /home/gzr/liliguang.keystore
- 1
- 2
2.SpringBoot配置SSL
文件放到项目根路径就可以了
3.然后配置application.properties
#端口号
server.port=8443
#你生成的证书名字
server.ssl.key-store=tomcat.keystore
#密钥库密码
server.ssl.key-store-password=tomcat
server.ssl.keyStoreType=JKS
server.ssl.keyAlias:tomcat
此刻启动项目,所有url都需要https
以下代码则是配置tomcat,让https有针对的自动从http跳转并且跳转的是部分安全页面
package com.gzr;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringbootmyApplication {
public static void main(String[] args) {
SpringApplication.run(LLGApplication.class, args);
}
/**
* it's for set http url auto change to https
*/
@Bean
public EmbeddedServletContainerFactory servletContainer(){
TomcatEmbeddedServletContainerFactory tomcat=new TomcatEmbeddedServletContainerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint=new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");//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);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
此时运行http://localhost:8080/user/user.html,会自动跳转到https://localhost:8888/user/user.html
4.总结
在进行证书制作并运行ssl的时候,其实都是一样的,我们从jdk里面的证书就可以看出只要生成一个证书并且部署到项目上就行了,阿里云的证书可以免费申请,但是域名就不知道了,所以没有接着测试,一般https这些会使用nginx来进行代理,之后再继续探讨。