SpringCloud配置中心/配置加密
- 上一节讲到:config客户端回去config服务器读取配置,而config服务器则是去SVN仓库读取配置
- 在实际应用中,会设计到许多敏感数据(如:数据库密码),这些敏感数据会保存到SVN仓库中
- SpringCloud为这部分敏感数据提供加密/解密功能,对加密后的密文传输给客户端之前会进行解密
- 配置服务器支持对称(AES)/非对称加密(RSA)
1、安装JCE
2、加密和解密的端点
- /encrypt
- /decrypt
- 对称加密:加密和解密使用相同密钥
- 非对称加密:加密和解密使用不同密钥
2.1、服务器配置密钥
encrypt:
key: aitemi
## 为了方便测试,关闭安全管理
management:
security:
enabled: false
- 加下来编写一个HttpClient客户端去请求加密接口,并且传入需要加密的内容
2.2、加密调用测试
package com.atm.cloud
import org.apache.http.Consts
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
public class EncryptMain {
public static void main(String[] args) throws Exception {
CloseableHttpClient client = HttpClients.createDefault()
// 发送post请求
HttpPost post = new HttpPost("http://localhost:8888/encrypt")
// 设置请求的参数,对20180323进行加密,编码格式为UTF-8
HttpEntity entity = new StringEntity("20180323", Consts.UTF_8)
post.setEntity(entity)
HttpResponse response = client.execute(post)
System.out.println(EntityUtils.toString(response.getEntity()))
}
}
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>


2.3、解密调用测试
package com.atm.cloud
import org.apache.http.Consts
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
public class DecryptMain {
public static void main(String[] args) throws Exception {
CloseableHttpClient client = HttpClients.createDefault()
// 发送post请求
HttpPost post = new HttpPost("http://localhost:8888/decrypt")
// 设置请求的参数,对2cdf324e7d8c6271d883a7a9bdcac532d027141545f1fed273f8c2b803bc3e9d进行解密,编码格式为UTF-8
HttpEntity entity = new StringEntity("2cdf324e7d8c6271d883a7a9bdcac532d027141545f1fed273f8c2b803bc3e9d", Consts.UTF_8)
post.setEntity(entity)
HttpResponse response = client.execute(post)
System.out.println(EntityUtils.toString(response.getEntity()))
}
}

2.4、SVN存储加密数据

- ‘{cipher}密文’
- 只需要在yml中修改如下内容
test:
user:
name: aitemi
## 使用'{cipher} xxxx',xxxx代表需要解密的内容
## 在properties文件中不需要单引号
password: '{cipher}fca358013a71b250c4a4a40cd844fdd6d47f8ddc13fb366893fa1ef29c79d55c'

3、非对称加密
3.1、非对称加密

keytool -genkeypair -alias "myKey" -keyalg "RSA" -keystore "D:\keys\mykey.keystore"


- 将密钥对拷贝到服务器项目resources目录下

3.2、配置密钥对
encrypt:
keyStore:
location: classpath:/myKey.keystore
password: 123456
alias: myKey
secret: 123456

