SpringBoot下配置文件密码加密
Jasypt方式
一、导入配置文件
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency>
二、执行测试:生成密文密码
1.加盐:在application.properties中添加(自行设置),加/解密规则
#加/解密的时候用这个密码(盐值) jasypt.encryptor.password=zhangzhixi
2.执行测试文件:用于生成密码
import org.jasypt.encryption.StringEncryptor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /** * @ClassName com.zhixi.MyTest * @Author zhangzhixi * @Description * @Date 2022-4-22 10:57 * @Version 1.0 */ @SpringBootTest public class MyTest { @Autowired StringEncryptor stringEncryptor; @Test public void encryptorTest() { /*你的数据库密码*/ String passwd = stringEncryptor.encrypt("you-passwd"); System.out.println("加密密码是:" + passwd); System.out.println("解密密码是:"+stringEncryptor.decrypt(passwd)); } }
3.将生成的密码添加到数据库连接信息中:注意要使用ENC()包裹住生成的密码
spring.datasource.password=ENC(LVwCic/f7N63bxiCWAoCq0IMOVjjGr69zalGkmbOaPVSz+k74hyVvdPLdBuo5)
4.删除加盐的规则
这个主要是防止别人看到你的加盐规则,可以得到你的密码。
三、启动项目
如果注释了加盐的规则,就需要在项目启动的时候做一些操作:
IDEA启动项目:
命令行下启动项目,加上参数:--jasypt.encryptor.password=xxx
MybatisPlus方式
一、对用户名密码进行加密
@Test void contextLoads() { // 生成 16 位随机 AES 密钥 String randomKey = AES.generateRandomKey(); System.out.println("randomKey = " + randomKey); // 利用密钥对用户名加密 String username = AES.encrypt("用户名", randomKey); System.out.println("username = " + username); // 利用密钥对用户名加密 String password = AES.encrypt("密码", randomKey); System.out.println("password = " + password); }
randomKey = c8ed174fb0031289 username = QaOmqbHmbcFvvuIhhiraRw== password = oeYaNABGKKdLOkoENzhu6Q==
二、修改配置文件
# 密文要以 mpw:开头 spring.datasource.username=mpw:FimaBnyC5LV2kMHCkpWNbw== spring.datasource.password=mpw:GAG2GYMVA5R2Mj9rfjNiig==
三、启动项目
java -jar方式
java -jar mybatis-query-11-1n-nn-0.0.1-SNAPSHOT.jar --mpw.key=ce9341eb0c1eddf5
单元测试方式
@SpringBootTest(classes = MybatisQuery111nNnApplication.class, args = "--mpw.key=ce9341eb0c1eddf5")
IDEA方式