SpringBoot整合Druid,密码加密
2024-09-05 17:40:00
1.application.yml配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/jby?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
# 密文
password: 'f687101570bae7ce4d313c2b4440f4ae'
initialSize: 100
minIdle: 100
maxActive: 200
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 'x' FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: config,stat
2. 构建UmspscDataSource类,继承DruidDataSource类
@Slf4j
public class UmspscDataSource extends DruidDataSource {
private String passwordDis;
/**
* 密匙
*/
private final static String Pkey ="1234565437892132";
@Override
public String getPassword(){ if(StringUtils.isNotBlank(passwordDis)){return passwordDis;}
String encPassword = super.getPassword();
if(null==encPassword){
return null;
}
log.info("数据库密码加解密,{"+encPassword+"}");
try{
// 密文解密,解密方法可以修改
String key = HexUtil.encodeHexStr(Pkey);
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes());
passwordDis = aes.decryptStr(encPassword, CharsetUtil.CHARSET_UTF_8);
return passwordDis;
}catch (Exception e){
log.error("数据库密码解密出错,{"+encPassword+"}");
log.error(LogUtil.e(e));
throw new AppException("数据库密码解密失败!", e);
}
}
}
3.初始化DataSource类
@Component
public class CommonBeanFactory {
@Bean(name = "dataSource", autowire = Autowire.NO, initMethod = "init")
@Primary
@ConfigurationProperties(ignoreUnknownFields = false,prefix="spring.datasource")
public DruidDataSource dataSource() {
DruidDataSource druidDataSource = new UmspscDataSource();
return druidDataSource;
}
}
*******************************
构建密文
@Slf4j
public class Main { public static void main(String[] args) {
//明文
String content = "123456";
//密匙
String pkey = "1234565437892132";
log.info("密匙:" + pkey);
String key = HexUtil.encodeHexStr(pkey);
//构建
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes()); //加密为16进制表示
String encryptHex = aes.encryptHex(content);
log.info("密文:" + encryptHex);
//解密为字符串
String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
log.info("明文:" + decryptStr);
}
}
最新文章
- [翻译] ORMLite document -- How to Use Part (一)
- Hibernate实现向数据库插入一条数据全过程(Study By Example)
- Mysql date_sub函数使用
- aspose.word 查找文本并加下划线
- mysql 数据库性能追踪与分析
- MySQL批量更新死锁案例分析--转载
- Linux基本操作 2-----Linux文件系统基本结构
- ubuntu初学成长记录
- ASP.NET MVC编程——验证、授权与安全
- Leetcode_116_Populating Next Right Pointers in Each Node
- LOJ_6178_景区路线规划
- [asp.net core 源码分析] 01 - Session
- c/c++ 继承与多态 容器与继承1
- MySQL Innodb数据库误删ibdata1后MySQL数据库的恢复案例
- mimikaz常用命令
- MySQL基础之 恢复数据和数据库迁移
- Android 模拟输入那点事
- Spring-Session实现Session共享实现原理以及源码解析
- java与C#、.NET AES加密、解密 解决方案
- R语言比较运算符和逻辑运算符