Spring Boot使用jasypt对配置文件中敏感信息进行加密

日常使用中,数据库、redis、kafka等信息一般会配在配置文件中,而且以明文的方式,这样就很不安全,容易造成重要信息的泄露。
正好之前我们做项目的时候用到 jasypt 进行加密存储。
最近需要修改数据库密码,正好记录一下这个知识点。

1、引入依赖

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

2、加密

在 maven 仓库找到 jasypt 的 jar 包,

打开命令行窗口

命令为:

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=123456 algorithm=PBEWithMD5AndDES input=lixj
  • password:加密的私钥
  • input:要加密的信息

如图所示,私钥为123456,lixj 加密后的密文为:resHmHRaVO6d7CcyJLHv8Q==
如果不喜欢可以执行多次,每次生成的密文都不一样。

3、配置

将加密后的信息配置在配置文件,使用 ENC 关键字。

添加 @EnableEncryptableProperties

应用启动时需要添加以下启动参数,不然会解密不出来,导致启动失败。

-Djasypt.encryptor.password=123456 -Djasypt.encryptor.algorithm=PBEWithMD5AndDES

4、解密

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI  password=123456 algorithm=PBEWithMD5AndDES input="resHmHRaVO6d7CcyJLHv8Q=="

5、java 代码实现加解密


import org.jasypt.intf.service.JasyptStatelessService;


public enum JasyptEncryptUtil {
    /**
     * 唯一实例,使工具类单例化
     */
    INSTANCE;

    private static JasyptStatelessService jasyptStatelessService = new JasyptStatelessService();

    // 加密
    public static String encrypt(String input, String password, String algorithm) {
        return jasyptStatelessService.encrypt(input, password, null, null, algorithm, null, null, null, null,
                null, null, null, null, null, null,
                null, null, null, null, null, null, null);
    }

    // 解密
    public static String decrypt(String input, String password, String algorithm) {
        return jasyptStatelessService.decrypt(input, password, null, null, algorithm, null, null, null, null,
                null, null, null, null, null, null, null,
                null, null, null, null, null,null);
    }

    /**
     * 使用默认加密算法:PBEWithMD5AndDES
     * 加密
     * @param input    要加密的内容
     * @param password 密钥
     * @return
     */
    public static String encrypt(String input, String password) {
        return encrypt(input, password, "PBEWithMD5AndDES");
    }

    /**
     * 使用默认加密算法:PBEWithMD5AndDES
     * 解密
     * @param input   要解密的内容
     * @param password  密钥
     * @return
     */
    public static String decrypt(String input, String password) {
        return decrypt(input, password, "PBEWithMD5AndDES");
    }

    public static void main(String[] args) {
        System.out.println(encrypt("lixj", "123456"));
        System.out.println(decrypt("9HhTbI9i6bh7D2tAVDYblA==", "123456"));
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值