Jasypt对SpringBoot配置文件里的重要信息加密

一、pom文件引入jar包

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>

二、新建JasyptDemo 工具类

  1. 设置秘钥 String KEY = "自定义秘钥";
  2. 两种加密算法任选一种对要加密的字符串加密

 

import org.jasypt.util.text.BasicTextEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;

public class JasyptDemo {
    public static final String KEY = "myKey";
    public static void main(String[] args) {
        System.out.println("username:"+pbeWithMD5AndDES("root"));
        System.out.println("password:"+pbeWithMD5AndDES("123456"));
        System.out.println("username:"+pbeWithMD5AndTripleDES("root"));
        System.out.println("password:"+pbeWithMD5AndTripleDES("123456"));
    }

    /**
     * PBEWithMD5AndDES加密法.
     * @param key 秘钥
     * @param str 要加密的字符串
     * @return 加密字符串
     */
    public static String pbeWithMD5AndDES(String str) {
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        //加密所需秘钥
        textEncryptor.setPassword(KEY);
        //加密
        return textEncryptor.encrypt(str);
    }

    /**
     * PBEWithMD5AndTripleDES加密法.
     * @param key 秘钥
     * @param str 要加密的字符串
     * @return 加密字符串
     */
    public static String pbeWithMD5AndTripleDES(String str) {
        StrongTextEncryptor textEncryptor = new StrongTextEncryptor();
        //加密所需秘钥
        textEncryptor.setPassword(KEY);
        //加密
        return textEncryptor.encrypt(str);
    }
}

 看下源码:

        

 

 

 加密后的值,每次运行加密的值都不一样不用奇怪。

username:Yr9iXBshBnTwweou9L2l+Q==
password:LihhSZSYNDIbr+7JC8b4NA==
username:DDb4utnzoa7GUznEIZ85Lg==
password:gfOTzaxPbe3MwfojkrlFGw==

 三、properties文件使用加密的值

注意:!!!

使用方法:ENC(加密串)

##datasource info
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=ENC(Yr9iXBshBnTwweou9L2l+Q==)
spring.datasource.password=ENC(LihhSZSYNDIbr+7JC8b4NA==)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.minimum-idle=5
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

运行时在 run conf 中配置秘钥

-Djasypt.encryptor.password=myKey

myKey是自定义的key!

 

四、启动jar包时 要指定自己定义的秘钥

java -jar -Djasypt.encryptor.password=myKey xxx.jar

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值