简单使用
1、引入依赖 jasypt-spring-boot-starter
如果项目使用@SpringBootApplication或@EnableAutoConfiguration注解,在pom中加入以下依赖即可对整个Spring的环境的配置信息进行加密解密。
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2、yml文件配置
jasypt:
encryptor:
bean: encryptorBean
#encryptorBean 配置
3、自定义加密器配置类
这里是自定义加密器方式,也可使用默认或者其他方式。
@EnableCustomConfig
@EnableCustomSwagger2
@EnableRyFeignClients
//@Import({WebConfig.class, MqttSenderConfig.class})
//@Import({MqttSenderConfig.class})
@Import(RedissonConfig.class)
@SpringBootApplication
public class WisdomCtsApplication {
public static void main(String[] args) {
SpringApplication.run(WisdomCtsApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 终端消息服务启动成功 ლ(´ڡ`ლ)゙ \n" +
" ██████ ██ ██ █████ █████ █████ ██████ ██████\n" +
" ██░░░░ ░██ ░██ ██░░░██ ██░░░██ ██░░░██ ██░░░░ ██░░░░ \n" +
"░░█████ ░██ ░██░██ ░░ ░██ ░░ ░███████░░█████ ░░█████ \n" +
" ░░░░░██░██ ░██░██ ██░██ ██░██░░░░ ░░░░░██ ░░░░░██\n" +
" ██████ ░░██████░░█████ ░░█████ ░░██████ ██████ ██████ \n" +
"░░░░░░ ░░░░░░ ░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░░ \n");
}
//jasypt
@Bean(name = "EncryptorBean")
static public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("7g3PjDdatx57");
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
}
4、加密解密工具类
package com.zzg.common.core.utils;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
public class JasyptEncryptorUtils {
private static final String salt = "7g3PjDdatx57";
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(salt);
}
private JasyptEncryptorUtils() {
}
/**
* 明文加密
*
* @param plaintext
* @return
*/
public static String encode(String plaintext) {
//System.out.println("明文字符串:" + plaintext);
String ciphertext = basicTextEncryptor.encrypt(plaintext);
//System.out.println("加密后字符串:" + ciphertext);
return ciphertext;
}
/**
* 解密
*
* @param ciphertext
* @return
*/
public static String decode(String ciphertext) {
//System.out.println("加密字符串:" + ciphertext);
ciphertext = "ENC(" + ciphertext + ")";
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
return plaintext;
}
//System.out.println("解密失败");
return "";
}
}