如何将yml文件中暴露的数据库用户名和密码由明文改为密文,提高安全性。
个人觉得是最简单的方式实现
yml代码,用户名密码使用文章后面提供的加密算法或者自行寻找方法
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
username: 这是密文用户名
password: 这是密文密码
配置DataSource的bean(加密解密方法可自行寻找)
@Configuration
public class DataSourceConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Bean
@Primary
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl(url);
// 这里把从yml文件拿到的用户名密码解密即可
druidDataSource.setUsername(SymmetricCryptoUtil.decString(username));
druidDataSource.setPassword(SymmetricCryptoUtil.decString(password));
druidDataSource.setDriverClassName(driverClassName);
return druidDataSource;
}
提供一个网上找的hutool的加密解密类(https://blog.csdn.net/Dong_Zi8/article/details/125196560)
public class SymmetricCryptoUtil {
/**
* 16字节
*/
private static final String ENCODE_KEY = "1234567812345678";
private static final String IV_KEY = "0000000000000000";
/**
* 加密
* @param string string
* @return
*/
public static String encString(String string){
return encryptFromString(string, Mode.CBC, Padding.ZeroPadding);
}
public static String decString(String string) {
return decryptFromString(string, Mode.CBC, Padding.ZeroPadding);
}
public static String encryptFromString(String data, Mode mode, Padding padding) {
AES aes;
if (Mode.CBC == mode) {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
new IvParameterSpec(IV_KEY.getBytes()));
} else {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
}
return aes.encryptBase64(data, StandardCharsets.UTF_8);
}
public static String decryptFromString(String data, Mode mode, Padding padding) {
AES aes;
if (Mode.CBC == mode) {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
new IvParameterSpec(IV_KEY.getBytes()));
} else {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
}
byte[] decryptDataBase64 = aes.decrypt(data);
return new String(decryptDataBase64, StandardCharsets.UTF_8);
}
}
完毕
标签:AES,用户名,String,aes,mode,KEY,mysql,new,springboot From: https://www.cnblogs.com/kmanngg/p/16977535.html