生成加密串
public class Encryptor {
public static void main(String[] args) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword("mysalt");//自定义加密盐
String myEncryptedPassword = textEncryptor.encrypt("jdbcpasword");
System.out.println("Encrypted DB password: " + myEncryptedPassword );
}
}
jdbc连接数据库密码设置为加密的使用ENC()
password: ENC(myEncryptedPassword )
一、.springMvc
1.引入包
<dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt-spring4</artifactId> <version>1.9.2</version> </dependency>
2.创建一个自定义DataSource 项目使用什么JDBC组件按自己项目进行修改,我的项目是Druid JDBC组件所以继承了Druid
public class CustomDruidDataSource extends DruidDataSource { Pattern pattern = Pattern.compile("^ENC\\((.+)\\)$"); // 创建一个 Jasypt 加密器实例 StandardPBEStringEncryptor encryptor; public CustomDruidDataSource() { super(); encryptor = new StandardPBEStringEncryptor(); String password = System.getProperty("jasypt.encryptor.password"); if (StringUtils.isNotBlank(password)) { encryptor.setPassword(password); } } @Override public void setUsername(String username) { String realUserName = username; Matcher matcher = pattern.matcher(username); if (matcher.matches()) { String encryptedUsername = matcher.group(1); realUserName = encryptor.decrypt(encryptedUsername); } super.setUsername(realUserName); } @Override public void setPassword(String password) { String realPassword = password; Matcher matcher = pattern.matcher(password); if (matcher.matches()) { String encryptedPassword = matcher.group(1); realPassword = encryptor.decrypt(encryptedPassword); } super.setPassword(realPassword); } }
3.applicationContext.xml修改配置修改数据库配置的数据源为自定义的DataSource
<bean id="dataSource" class="com.*.*.config.CustomDruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_user}" /> <property name="password" value="${jdbc_password}" /> </bean>
4.启动命令增加VM参数
4.1本地tomcat VM参数增加
-Djasypt.encryptor.password=mysalt
4.2服务器TOMCAT 修改
tomcat/bin/catalina.sh JAVA_OPTS="$JAVA_OPTS -Djasypt.encryptor.password=mysalt"
二、springboot
1.引入包 <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency>
2.启动命令增加
-Djasypt.encryptor.password=mysalt//自定义加密盐