工程中的配置文件若是把数据库的用户名密码写成明文的话是一件很危险的事情,以前也看见网上说能够对密码进行加密,用的时候再解密,所以今天我就尝试如何在spring boot 中的项目中实现关键信息的加密解密,并记录下来。html
jasypt
Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.
这是摘抄自Jasypt官网的一句描述,重点就是简单方便,同时和spring可以很好的集成,尤为是还提供了对spring boot的支持,能够参考starter的实现:https://github.com/ulisesbocchio/jasypt-spring-bootjava
-
Maven依赖
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>1.14</version> </dependency>
http://central.maven.org/maven2/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jargit
-
加密密码
加密命令以下(红色部分表明须要加密的密码):github
java -cp F://.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="test123" password=e9fbdb2d3b21 algorithm=PBEWithMD5AndDES
命令回显以下(红色部分是加密后的密文):spring----ENVIRONMENT----------------- Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.121-b13 ----ARGUMENTS------------------- algorithm: PBEWithMD5AndDES input: test123 password: e9fbdb2d3b21 ----OUTPUT---------------------- ArGx5ir2xs+CmXRhMnThpQ==
-
在程序中设置密文
在程序中设置密文须要使用以下格式:docker
ENC(密文) 如: spring.datasource.password=ENC(ArGx5ir2xs+CmXRhMnThpQ==)
在程序中获取到的spring.datasource.password会自动转换成明文内容(test123)。数据库
-
配置密文密码
在启动命令中配置JVM参数(jasypt.encryptor.password),注入加密密文的密码。
如:mavenjava -Dfile.encoding=UTF8 -Djasypt.encryptor.password=e9fbdb2d3b21 -jar -Xmx512m settlement.jar
注:在docker容器中密文的密码能够设置成环境变量(如:JASYPT_PASSWORD ),上述命令能够修改成:ide
java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_PASSWORD} -jar -Xmx512m settlement.jar
- 参考文档
https://www.ricston.com/blog/encrypting-properties-in-spring-boot-with-jasypt-spring-boot/
https://github.com/ulisesbocchio/jasypt-spring-boot