jasypt是一个简单方便的第三方加解密库,可以快速的集成到springboot环境中,在3.x之后默认基于的是PBEWITHHMACSHA512ANDAES_256加密算法;
如果需要自定义加密算法可以参考下面的方式,参考:
https://github.com/ulisesbocchio/jasypt-spring-boot
<!-- 数据库加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<!-- 如果要使用SM4加密,就需要引入下面的jar -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.60</version>
</dependency>
<!-- hutool的工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.9</version>
</dependency>
编写自定义的加解密工具类(这里使用SM4加密算法,引用的是hutool的工具类)
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
* jasypt 自定义数据库密码加密器 - SM4加密算法
* @author jiaqiankun
@Component("customStringEncryptor")
public class CustomStringEncryptor implements StringEncryptor {
@Value("${jasypt.encryptor.salt}")
private String salt;
@Override
public String encrypt(String message) {
SymmetricCrypto sm4 = SmUtil.sm4(salt.getBytes());
String encryptHex = sm4.encryptHex(message);
return encryptHex;
@Override
public String decrypt(String encryptedMessage) {
SymmetricCrypto sm41 = SmUtil.sm4(salt.getBytes());
String decryptStr = sm41.decryptStr(encryptedMessage, CharsetUtil.CHARSET_UTF_8);
return decryptStr;
在配置文件中指定自定义的加密器并定义一个salt
#密码
spring:
datasource:
url: jdbc:mysql://localhost:3306/fmbs?characterEncoding=utf8&useSSL=true
username: root
#ENC是一个标识,可以在下方通过jasypt.encryptor.property.prefix
#和jasypt.encryptor.property.suffix进行指定,默认是enc(密文)
password: ENC(a44625760f8fc68e8d3c6e3f18f898cd)
#属性文件加密
jasypt:
encryptor:
#salt必须为16位字符串,如果使用默认算法,此处的salt应该改为password,自定义随意命名,
#在customStringEncryptor中注入正确即可
salt: ya024uspkidtclu3
bean: customStringEncryptor