Java Springboot自定义Jasypt解密
1、pom
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.4</version>
</dependency>
2、程序主函数添加注解
@EnableEncryptableProperties
3、加密解密封装类
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig; public class JasyptUtils { private final static String JASYPT_PASSWORD = "your_password"; private final static String JASYPT_ALGORITHM = "PBEWithMD5AndDES"; // private final static String JASYPT_ALGORITHM = "PBEWITHHMACSHA512ANDAES_256"; /** * 加密 * * @param plaintext 明文 * @return */ public static String encrypt(String plaintext) { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig(); // 指定算法 config.setAlgorithm(JASYPT_ALGORITHM); // 指定秘钥,和yml配置文件中保持一致 config.setPassword(JASYPT_PASSWORD); encryptor.setConfig(config); // 生成加密数据 return encryptor.encrypt(plaintext); } /** * 解密 * * @param data 加密后数据 * @return */ public static String decrypt(String data) { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig(); config.setAlgorithm(JASYPT_ALGORITHM); config.setPassword(JASYPT_PASSWORD); encryptor.setConfig(config); // 解密数据 return encryptor.decrypt(data); } }
4、自定义解析类
import cn.nosya.study.util.JasyptUtils; import org.jasypt.encryption.StringEncryptor; import org.springframework.stereotype.Component; @Component public class CustomDecryptor implements StringEncryptor { @Override public String encrypt(String s) { return JasyptUtils.encrypt(s); } @Override public String decrypt(String encrypted) { return JasyptUtils.decrypt(encrypted); } }
5、配置文件指定上面的解析类
jasypt.encryptor.bean=customDecryptor
6、bat文件制作加密解密工具
加密: java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=0123456789abcdeffedcba9876543210 algorithm=PBEWithMD5AndDES input=123456! 解密: java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="加密后的密文" password=jasypt配置密码 algorithm=PBEWithMD5AndDES
有些事情,没经历过不知道原理,没失败过不明白奥妙,没痛苦过不了解真谛。临渊羡鱼,不如退而结网!

浙公网安备 33010602011771号