一、HTTPS (全稱:Hyper Text Transfer Protocol over SecureSocket Layer),是以安全為目標的 HTTP 通道,在HTTP的基礎上通過傳輸加密和身份認證保證了傳輸過程的安全性 [1] 。HTTPS 在HTTP 的基礎下加入SSL,HTTPS 的安全基礎是 SSL,因此加密的詳細內容就需要 SSL。 HTTPS 存在不同於 HTTP 的默認端口及一個加密/身份驗證層(在 HTTP與 TCP 之間)。這個系統提供了身份驗證與加密通訊方法。它被廣泛用於萬維網上安全敏感的通訊。
二、生成密鑰(JDK生成方式)
1、接收方(服務端)
keytool -genkey -alias server -keyalg RSA -keystore server.jks
2、接收方(服務端)導出證書
keytool -export -file server.cer -alias server -keystore server.jks
3、導出發送方密鑰
keytool -import -keystore client.jks -file server.cer -alias client
4、最后有3個文件
三、springboot作為服務端配置
server: ssl: enabled: true key-alias: server key-store-type: jks key-store: classpath:jks/server.jks key-password: <password> key-store-password: <password>
四、RestTemplate作為客戶端配置
1、需要在springboot的基礎上加入httpclient依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
2、加入配置
import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; @Configuration public class RestConfiguration { @Bean public RestTemplate restTemplate() throws Exception { HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); //超時配置 factory.setReadTimeout(5000); factory.setConnectTimeout(2000); //https SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(new ClassPathResource("jks/client.jks").getFile(), "<password>".toCharArray()) .build(); //連接facotry SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); factory.setHttpClient(HttpClients.custom().setSSLSocketFactory(socketFactory).build()); return new RestTemplate(factory); } }
五、總結https不是難在配置,也是難在加密方式。目前國內很多都有考慮采用國標加密算法,而不是RSA的方式,所以這里需要自行考慮。