引入jar包
在项目的pom文件中引入对应的jar包,其中${jasypt.version}可以在pom文件中properties属性中定义。文章中使用的版本是2.1.0
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
添加启动类扫描
需要在springboot项目中的启动类,注解SpringBootApplication的scanBasePackages中添加“com.ulisesbocchio.jasyptspringboot”,这个是引入jar包的跟路径,这样才能扫描到引入jar包的config类
@SpringBootApplication(scanBasePackages = {"com.erge","com.ulisesbocchio.jasyptspringboot"})
public class ErbaogeApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ErbaogeApplication.class, args);
}
}
配置文件开启
配置文件开启解密,开启后springboot才会注入对应的config类,true代表开启
jasypt:
encryptor:
bootstrap: true
加密报文
加密报文需要设置盐、算法、输出类型等,示例加密方法提供的是工具默认加密算法,盐自行定义。将最终输出的字符串(假设输出666666)需要放在ENC(666666),其中ENC()是默认格式,直接将ENC(666666)替换明文。
public static void main(String[] args) {
String password = "j+UsiwNckWaaU="; //要加密的(数据库/redis等)密码
String salt = "mtOWc6"; //加密用的salt(密钥)
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations(1000);
config.setPoolSize(1);
if(StringUtils.isEmpty(salt)) {
config.setSaltGenerator(new RandomSaltGenerator());
salt = "";
} else {
config.setPassword(salt); // 加密的密钥
}
config.setStringOutputType("base64");
PooledPBEStringEncryptor pooledPBEStringEncryptor = new PooledPBEStringEncryptor();
pooledPBEStringEncryptor.setConfig(config);
String encryptedText = pooledPBEStringEncryptor.encrypt(password);
System.out.println("===== SALT: "+salt);
System.out.println("===== SRC: "+password);
System.out.println("===== ENCRYPTED: "+encryptedText);
}
相关配置
以上只是默认配置,只需要开启就可使用,还有一些相关配置,可以修改默认格式,指定加解密算法等。此处尚未验证相关配置,日后补充