springboot ENC jasypt加密敏感配置
pom中添加依赖:
<!-- 配置文件密码加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.3</version>
</dependency>
添加配置类:
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @description : 配置文件用户密码 加密配置类
*/
@Configuration
public class EncryptorConfig {
@Bean("jasyptStringEncryptor")
public StringEncryptor jasyptStringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("qwertyuiop123");
// config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256"); // 这个加密算法比较特殊,后期更新
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
}
测试方法:
import org.jasypt.util.text.BasicTextEncryptor;
import java.util.Scanner;
/***
* 配置文件用户密码加密/解密测试类
*/
public class CryptoUtilTest {
private static String KEY = "qwertyuiop123";
public static void main(String[] args) {
generatePassword();
decryptPassword();
}
/**
* 获取密文
*/
private static void generatePassword(){
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的salt(盐) 随便生成的随机数用做盐值
textEncryptor.setPassword(KEY);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入密码明文:");
String password = scanner.nextLine();
//要加密的数据(数据库的用户名或密码)
String enPassword = textEncryptor.encrypt(password);
//查看密码
System.out.println("密码密文是:");
System.out.println(enPassword);
}
/**
* 获取明文
*/
private static void decryptPassword(){
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的salt(盐) 随便生成的随机数用做盐值
textEncryptor.setPassword(KEY);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入密码密文:");
String password = scanner.nextLine();
//要加密的数据(数据库的用户名或密码)
String enPassword = textEncryptor.decrypt(password);
//查看密码
System.out.println("密码明文是:");
System.out.println(enPassword);
}
}
yml配置文件中修改用户名和密码:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test
username: ENC(2Hn+MUePaco1jG01mDi6JQ==)
password: ENC(Tui0/IQEjniy9LRB74QQC2Lz4j8zR4zS)
网友评论