1、引包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
2、配置加密盐值,用来进行加密, 自定义
jasypt:
encryptor:
password: EbfYki
3、数据库加密、其他如redis等也可以
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/unite?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
username: root
#原密码123456
password: ENC(t9cksZGhwkf2zXOMM7H5ug==)
driver-class-name: com.mysql.cj.jdbc.Driver
4、加密工具
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
/**
* Jasyp加解密工具类
*/
public class JasypUtils {
private static final String PBEWITHMD5ANDDES = "PBEWithMD5AndDES";
private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";
/**
* Jasyp2.x 加密(PBEWithMD5AndDES)
* @param value 待加密的原文
* @param password 加密秘钥
* @return java.lang.String
*/
public static String encryptWithMD5(String value, String password) {
// 1. 创建加解密工具实例
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
// 2. 加解密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm(PBEWITHMD5ANDDES);
config.setPassword(password);
encryptor.setConfig(config);
// 3. 加密
return encryptor.encrypt(value);
}
/**
* Jaspy2.x 解密(PBEWithMD5AndDES)
* @param encryptedText 待解密密文
* @param password 解密秘钥
* @return java.lang.String
*/
public static String decryptWithMD5(String encryptedText, String password) {
// 1. 创建加解密工具实例
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
// 2. 加解密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
config.setAlgorithm(PBEWITHMD5ANDDES);
config.setPassword(password);
encryptor.setConfig(config);
// 3. 解密
return encryptor.decrypt(encryptedText);
}
public static void main(String[] args) throws Exception{
try {
String value = "123456";
String password = "EbfYki";
String encryptWithMD5Str = encryptWithMD5(value, password);
String decryptWithMD5Str = decryptWithMD5(encryptWithMD5Str, password);
System.out.println("加密前原文:" + decryptWithMD5Str);
System.out.println("加密后密文:" + "ENC(" + encryptWithMD5Str + ")");
} catch (Exception e) {
e.printStackTrace();
}
}
}