使用 jasypt 加密配置文件信息
Jasypt 是一个加密算法库,用于在 Java 应用程序中实现加密和解密文本信息。它 jasypt 可以用于加密存储在数据库中的密码、保护敏感数据、加密文件等场景。
jasypt 加解密的过程:
- 事先通过将需要加密的参数使用加密工具得到的密文写入配置文件,并在配置文件中使用 ENC()“函数”(本质就是一个标记特征字符)进行标记;
- 应用启动的时候传入解密密钥,然后应用在读取配置参数键值的时候,如果发现键值中含有 ENC 标记,就将“ENC()”中的内容抽取出来,然后调用加解密接口(org.jasypt.encryption.StringEncryptor)的实现类进行解密,从而得到明文。加密操作同理。
引入依赖
1 2 3 4 5
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
|
编写工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package com.plume.config.util;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class JasyptUtil {
private static String password = "123456"; private static String prefix = "ENC("; private static String suffix = ")";
private static PooledPBEStringEncryptor encryptor;
static { encryptor = new PooledPBEStringEncryptor(); encryptor.setConfig(getConfig()); }
public static void main(String[] args) { String encrypt = encrypt("测试"); System.out.println(prefix + encrypt + suffix); String decrypt = decrypt(encrypt); System.out.println(decrypt); }
public static String encrypt(String encrypt){ return encryptor.encrypt(encrypt); }
public static String decrypt(String encrypt){ return encryptor.decrypt(encrypt); }
public static SimpleStringPBEConfig getConfig(){ SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(password); config.setAlgorithm("PBEWithMD5AndDES"); config.setKeyObtentionIterations(1000); config.setPoolSize(1); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator"); config.setStringOutputType("base64"); return config; } }
|
修改配置文件
- 把盐值写入配置文件(建议将盐值写入本地 idea 运行时配置中 -Djasypt.encryptor.password=123456)
- 把明文密码替换为工具类生成的密文,并用 ENC()包着
1 2 3 4 5
| pld: host: ENC(33GHKlw9pCYqeWVrhjhjQ+dKMhfpkVgl6q) mysql-port: 3306 nacos-port: 8848 redis-port: 6379
|
配置文件格式
1 2 3 4 5 6 7 8 9 10 11 12
| jasypt: encryptor: password: 123456 algorithm: PBEWithMD5AndDES iv-generator-classname: org.jasypt.iv.NoIvGenerator property: prefix: ENC( suffix: )
|