需求引入
当我们需要对SpringBoot项目的配置文件中的信息进行加密时,如数据库密码等,此时我们可以使用Jasypt来实现。
解决方案
第一步,引入Jasypt依赖
1 2 3 4 5
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
|
第二步,编写工具类
JasyptUtils:
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
| package com.keafmd.springdemo.utils;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.StandardPBEByteEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class JasyptUtils {
public static String encryptPwd(String password, String value) { PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor(); encryptOr.setConfig(cryptOr(password)); String result = encryptOr.encrypt(value); return result; }
public static String decyptPwd(String password, String value) { PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor(); encryptOr.setConfig(cryptOr(password)); String result = encryptOr.decrypt(value); return result; }
public static SimpleStringPBEConfig cryptOr(String password) { SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(password); config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM); config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName(null); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); return config; }
public static void main(String[] args) { System.out.println(encryptPwd("keafmd", "123456")); } }
|
第三步,修改配置文件
- 把盐值写入配置文件
- 把明文密码替换为工具类生成的密文,并用ENC()包着
eg:
1 2 3 4 5 6 7 8 9 10
| spring: datasource: username: root password: ENC(aXcmM77CmYgj67mBxQgI2A==) url: jdbc:mysql://XXXX:XX/tt?useUnicode=true&characterEncoding=UTF-8&useSSL=false jasypt: encryptor: password: keafmd
|
以上就是配置文件加密(Jasypt的简单使用)的全部内容
版权声明:keafmd
原创博主:牛哄哄的柯南
博主原文链接:https://keafmd.top/
加油!
共同努力!
Keafmd