springboot 集成 jasypt
springboot 集成 jasypt
Jasypt不简介了,懒得在官网copy, 直接传送官网
说啥都假的,简单粗暴直接上代码
- 引入依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
- 配置加密参数
2.1 使用 properties文件配置jasypt.encryptor.password=jasypt
2.2 使用 yml文件配置
jasypt:
encryptor:
password: jasypt
除了以上两种配置个人推荐使用启动参数配置
idea 配置方法
- 两种生成加密密匙方式
3.1 使用spring boot单元测试
3.2 使用工具类import org.jasypt.encryption.StringEncryptor; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class JasyptTest { @Autowired private StringEncryptor stringEncryptor; @Test public void encryptPwd() { //加密123456 String result = stringEncryptor.encrypt("123456"); System.out.println(result); } }
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; /** * @author shuzhuo * @date 2019/1/9 9:56 */ public class JasyptUtil { /** * Jasypt生成加密结果 * @param password 配置文件中设定的加密密 * @param value 加密值 * @return */ public static String encyptPwd(String password,String value){ PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); encryptor.setConfig(cryptor(password)); String result = encryptor.encrypt(value); return result; } /** * 解密 * @param password 配置文件中设定的加密密码 * @param value 解密密文 * @return */ 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("PBEWithMD5AndDES"); config.setKeyObtentionIterations("1000"); config.setPoolSize("1"); config.setProviderName("SunJCE"); config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); config.setStringOutputType("base64"); return config; } public static void main(String[] args){ //加密 System.out.println(encyptPwd("jasypt","123456")); //解密 System.out.println(decyptPwd("jasypt","lnzpDZItgjAntHqsYPFTew==")); } }
- 将生成的加密密匙配置在配置文件中即可,ENC 是约定的关键字,在启动时会解析所有 PropertySource 中的加密属性。
4.1 这里更改yml配置中连接数据库的密码
spring:
datasource:
password: ENC(lnzpDZItgjAntHqsYPFTew==)
如果是使用启动参数配置打包为jar 或war怎么配置呢?
jar: 命令:java -Djasypt.encryptor.password=jasypt -jar xxx.jar
war:
到Tomcat的bin目录下,打开文件catalina.bat/catalina.sh,添加如下参数,然后保存
加上启动参数配置
window:catalina.bat
set JAVA_OPTS="-Djasypt.encryptor.password=jasypt"
Linux:catalina.sh
JAVA_OPTS="-Djasypt.encryptor.password=jasypt"
更多请参考 jasypt github 文档