SSL(Secure Sockets Layer 安全套接層),及其繼任者傳輸層安全(Transport Layer Security,TLS)是為網絡通信提供安全及數據完整性的一種安全協議。TLS與SSL在傳輸層對網絡連接進行加密。
1.生成證書
使用JDK的bin目錄下的keytool生成,關於keytool簡單使用方法如下:
這里只研究其生成證書的方法,生成證書的命令是-genkey,如下:
上面也都解釋了每個參數的意思,下面研究其生成:
keytool.exe -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore G:/keystore.p12 -validity 3650
注意:上面的名字與姓氏應該輸入的是域名,其他密碼需要輸入,而且需要記住,其他地區信息可以不寫。
代碼此將生成名為keystore.p12
的PKCS12密鑰庫文件,證書別名為tomcat。
2.Springboot中使用上面的證書
將上面的證書復制到項目中,我是放在項目 根路徑,如下:
配置application.properties使用SSL:
############################################################ # # HTTPS相關配置 # ############################################################ server.ssl.key-store:keystore.p12 server.ssl.key-store-password: 111222 server.ssl.keyStoreType: PKCS12 server.ssl.keyAlias: tomcat
當然可以以 ver.ssl.key-store=G:/keystore.p12 的方式指定證書位置。
啟動測試:
3.在獨立的tomcat中使用SSL配置https訪問
這個需要重新生成key,也就是上面的key在獨立的tomcat中會報錯。
1.再次生成key:
keytool -genkeypair -alias "tomcat" -keyalg "RSA" -keystore "g:\tomcat.keystore"
2.tomcat中server.xml配置SSL訪問
<!-- Define a SSL HTTP/1.1 Connector on port 8443 This connector uses the BIO implementation that requires the JSSE style configuration. When using the APR/native implementation, the OpenSSL style configuration is required as described in the APR/native documentation --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> --> <Connector port="443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" keystoreFile="G:/tomcat.keystore" keystorePass="111222" />
3.啟動訪問測試:
https訪問:
http訪問:
4.http的默認端口是80,https默認的端口是443;接下來我們配置tomcat只支持https訪問
將http端口請求注釋掉即可。
<!--<Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>--> <!--<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>-->