springboot 配置 jasypt加密,应用于配置文件数据库密码加密形式展现
1.pom.xml导入对应的包
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <build> <plugins> <plugin> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-maven-plugin</artifactId> <version>3.0.3</version> </plugin> </plugins> </build>
2.第二步:加盐(三种方式)
1..yml中 一般是本地开发的时候
jasypt:
encryptor:
password: xxxxx
在环境变量中配置 JASYPT_ENCRYPTOR_PASSWORD =xxx (xxx根据自己的密钥设置)
2.在Program arguments 中设置 --jasypt.encryptor.password=xxx 一般是在正式显示采用这种方式,谁也不知道你的密钥是多少
3.在vm arguments 中设置 -Djasypt.encryptor.password=xxx 一般是在正式显示采用这种方式,谁也不知道你的密钥是多少
第三步:编写测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package com.org; import org.jasypt.encryption.StringEncryptor; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith (SpringJUnit4ClassRunner. class ) @SpringBootTest public class EncryptorTest { @Autowired private StringEncryptor encryptor; @Test public void encry() { String username = encryptor.encrypt( "UserName" ); String password = encryptor.encrypt( "Password" ); System.out.println(username); //获取加密的name 7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu 在DB配置中替换 System.out.println(password); //获取加密的password 3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b 在DB配置中替换 } } |
第四步:替换DB配置信息
1 2 3 4 5 6 | spring: datasource: driver- class -name: com.mysql.cj.jdbc.Driver url: jdbc:mysql: //xx.x.x.xx:3306/zxxxx username: ENC(7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu) password: ENC(3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b) |
到这一步就OK了,如果需要自定义密文的前后缀,可如下设置:
1 2 3 4 5 | jasypt: encryptor: property: prefix: "ENC@[" suffix: "]" |
如果以上配置不能使用的时候可以在启动类加上注解
1 | @EnableEncryptableProperties |
1 | datasource 代码获取如下 |
1 2 3 4 5 6 7 8 9 10 11 | @Configuration @Order ( 3 ) public class DataSourceConfig { //@Primary @Bean ( "datasource" ) //@Qualifier("datasource") @ConfigurationProperties (prefix = "datasource.datasource" ) public DataSource defaultDataSource() { return DataSourceBuilder.create().build(); } } |
测试环境或者线上环境启动命令如下 在你的明令上添加上这个
-Djasypt.encryptor.password='xxxx'
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)