一、使用jasypt
加解密
第一种方式:
1、引入依赖
<!--springboot整合jasypt-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
2、编写加密工具
import org.jasypt.util.text.BasicTextEncryptor;
/**
* @ClassName: JasyptUtil
* @Description: 数据库账号密码加密工具类
* @Author: root
* @Date: 22-8-10 上午9:55
* @Version: 1.0
**/
public class JasyptUtil {
public static void main(String[] args) {
String account = "root";
String password = "123456";
BasicTextEncryptor encryptor = new BasicTextEncryptor();
//秘钥
encryptor.setPassword("ENCKEY");
//密码进行加密
String newAccount = encryptor.encrypt(account);
String newPassword = encryptor.encrypt(password);
System.out.println("加密后账号:" + newAccount);
System.out.println("加密后密码:" + newPassword);
}
}
加密后的账号密码:
3、更改配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
#使用ENC包住密文
username: ENC(gdVuzoI0etetyUesW0hddw==)
password: ENC(llDq/tbZ7t59TlvWxqQxQg==)
第二种方式:
1、引入依赖
<!--springboot整合jasypt-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
2、编写加密工具
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
/**
* @ClassName: JasyptUtil
* @Description: 数据库账号密码加密工具类
* @Author: root
* @Date: 22-8-10 上午9:55
* @Version: 1.0
**/
public class JasyptUtil {
public static void main(String[] arg) {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
/*配置文件中配置如下的算法*/
standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
/*配置文件中配置的password*/
standardPBEStringEncryptor.setPassword("ENCKEY");
/*要加密的文本*/
String name = standardPBEStringEncryptor.encrypt("root");
String password = standardPBEStringEncryptor.encrypt("123456");
/*将加密的文本写到配置文件中*/
System.out.println("name=" + name);
System.out.println("password=" + password);
}
}
加密后的账号密码:
3、更改配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
#使用ENC包住密文
username: ENC(lSuEGTBNYA6nh7sOEdhqgA==)
password: ENC(e1eF4h32Hk9mwDraYRqdOQ==)
说明:以上两种方式配置后可通过如下方式指定解密密钥:
1、项目启动时指定启动参数将密钥传入:
-Djasypt.encryptor.password=ENCKEY
2、在配置文件中配置密钥值:
jasypt:
encryptor:
#可指定也可不指定
algorithm: PBEWithMD5AndDES
password: EWRREWRERWECCCXC