21、Jasypt-SpringBoot配置文件信息加密
Jasypt(Java Simplified Encryption)是一個輕量級的Java加密庫,旨在簡化加密操作,使Java開發者能夠在應用程序中輕松地實現數據加密和解密。它支持多種常見的加密算法,并提供了易于使用的 API 和加密容器,幫助開發者保護敏感信息(如密碼、密鑰、API 密鑰、數據庫密碼等)。
最常見的加密算法包括:
1、PBEWithMD5AndDES:基于密碼短語的加密(使用 MD5 和 DES 算法)。
2、AES (Advanced Encryption Standard):一種對稱加密算法,通常用于較強的加密需求。
3、RSA:非對稱加密算法,用于公共密鑰加密。
4、PBKDF2:一種基于密碼的密鑰派生函數,用于增強密碼強度。
Jasypt-SpringBoot的基本用法:
1、POM依賴:
<!-- 加解密依賴-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2、YML配置:
# 加密配置 jasypt: encryptor: # 指定加密密鑰,生產環境建議放到啟動參數 password: your-secret # 指定解密算法,需要和加密時使用的算法一致 algorithm: PBEWithMD5AndDES # 指定initialization vector類型 iv-generator-classname: org.jasypt.iv.NoIvGenerator
3、自定義加解密工具類:
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.springframework.util.ObjectUtils; /** * 加解密工具類 */ public class EncrypDecryptUtil { /** * 加密 * * @param password 加密時使用的密碼 * @param value 需要加密的值 * @return */ public static String encypt(String password, String value) { if(ObjectUtils.isEmpty(value)){ return null; } StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setPassword(password); return encryptor.encrypt(value); } /** * 解密 * * @param password 解密時使用的密碼 * @param value 需要解密的值 * @return */ public static String decypt(String password, String value) { if(ObjectUtils.isEmpty(value)){ return null; } StandardPBEStringEncryptor decryptor = new StandardPBEStringEncryptor(); decryptor.setPassword(password); return decryptor.decrypt(value); } public static void main(String[] args) { // "your-secret": YML中配置 //加密 System.out.println(EncrypDecryptUtil.encypt("your-secret", "root")); System.out.println(EncrypDecryptUtil.encypt("your-secret", "root")); //解密 System.out.println(EncrypDecryptUtil.decypt("your-secret", "7SZVFKSF09DDdmLwM8pU9dGKw==")); } }
4、相關使用:
ENC(密文):用于標記加密數據,其中括號中的部分是加密后的內容

浙公網安備 33010602011771號