springboot jasypt
数据库明码写在配置文件里,有些不安全。自己写个简单的可逆的加密算法也行,不过用成熟的产品也许bug更少。本文介绍的是jasypt。
一、简单用法。加密码数据库密码。
1.pom.xml
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.5</version> </dependency>
2.配置application.yml
jasypt: encryptor: password: abc!@#123 # 加密的密钥,自定义即可,必填项 algorithm: PBEWithMD5AndDES # 指定解密算法 iv-generator-classname: org.jasypt.iv.NoIvGenerator
3.生成密码
@SpringBootApplication @Slf4j public class Application { @Value("${spring.datasource.password}") private String password; public static void main(String[] args) throws Exception { ConfigurableApplicationContext context=SpringApplication.run(Application.class, args); StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); //加密所需的salt(盐) encryptor.setPassword("abc!@#123"); //要加密的数据(数据库的用户名或密码) String username = encryptor.encrypt("testUserName"); String password = encryptor.encrypt("testPwd123456"); System.out.println("username:"+username); System.out.println("password:"+password); System.out.println("解密1:" + encryptor.decrypt(username)); System.out.println("解密2:" + encryptor.decrypt(password)); System.out.println("password:"+context.getBean(Application.class).password); } }4.将生成的密码放到配置文件里
spring: application: name: springboot datasource: driver-class-name: com.mysql.cj.jdbc.Driver password: 'ENC(JK9duTFjFY6vPdsBwZhfd+dzMK1bdwG8)' url: jdbc:mysql://localhost/javaidc_chengzhong?useUnicode=true&characterEncoding=UTF8&rewriteBatchedStatements=true username: testUserName
上面ENC()包起来的就是密码
5.可以测试运行了。
相关阅读
评论:
↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑