在做微服务项目集成的时候,配置中心服务端存储着很多既关键又重要的信息,比如连接数据库的配置、用户名、密码等等,对于这些重要信息如何加密呢?现在就来实现一个基于配置中心的加密方法,结合JDK自带的JCE。
一.安装JCEJDK下的JCE默认是有长度限制的,需要替换没有长度限制的JCE版本,下载地址:https://www.oracle.com/cn/java/technologies/javase-jce8-downloads.html把下载包里的两个jar包拷贝到JAVA_HOME/jre/lib/security下。
二、pom.xml文件中添加架包;
<!-- 引入配置中心start -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>3.1.3</version>
</dependency>
<!-- 引入配置中心end -->
三、启动类增加注解;
/**
* 启动类文件
* @author 程就人生
* @Date
*/
@EnableConfigServer
@SpringBootApplication
public class SpringBootJasyptDemoApplication2 implements CommandLineRunner{
@Value("${spring.datasource.password}")
private String password;
public static void main(String[] args) {
SpringApplication.run(SpringBootJasyptDemoApplication2.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("从配置文件中读取的密码为:" + password);
}
}
四、application.properties配置文件中增加配置;
# 本地的配置文件
spring.profiles.active=native
# 配置文件检索路径
spring.cloud.config.server.native.search-locations=classpath:/config
# 加密key
encrypt.key=0ab44bd43d6b18fcd5cd928d6faab1b8
五、启动项目;
1.查看加密功能:localhost:8080/encrypt/status

2.打开cmd执行加密解密;
使用encrypt 对123456进行加密:encrypt -d 123456;
再使用decrypt对加密过的文字进行解密。

3.将加密过的文字写入配置文件;
spring.datasource.password={cipher}c828dda9abbfb2382fdf39ad326727ac525156fa5c409e971e8e8eb9456b5fde
注意事项:需要加密的信息必须以{cipher}开头;
4.重新启动项目,读取配置;

为什么在CMD下可以进行加密工作呢?

这是因为在org.springframework.cloud.config.server.encryption包下,有一个EncryptionController类,它提供了加解密的入口。

5.如果不想在控制台进行加解密操作,那么可以通过以下配置关闭;
spring.cloud.config.server.enabled=false
参考官网文档:
https://docs.oracle.com/javase/7/docs/technotes/guides/security/crypto/CryptoSpec.html#ProviderArch
网友评论