jasypt对配置文件的数据加密与解密

介绍

  • Jasypt是一个Java库,可以使开发者不需太多操作来给Java项目添加基本加密功能,而且不需要知道加密原理。
  • Jasypt能够以很简单的方式为Java项目提供加密功能。
  • Jasypt还符合RSA标准的基于密码的加密,并提供了无配置加密工具以及新的、高可配置标准的加密工具。

作用

        在配置文件中写密文,程序启动后自动解密,再使用这个解密后的信息对MySQL或Redis等进行连接,可以隐藏一些配置文件中的敏感信息,如MySQL用户名密码、Redis密码等。

快速开始

导入依赖

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

加密数据

写一个main方法,加密数据库的用户名和密码,得到加密后的用户名和密码。

public static void main(String[] args) {
    StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
    /*配置文件中配置如下的算法*/
    standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
    /*配置文件中配置的password*/
    standardPBEStringEncryptor.setPassword("EWRREWRERWECCCXC");
    /*要加密的文本*/
    String username = standardPBEStringEncryptor.encrypt("root");
    String password = standardPBEStringEncryptor.encrypt("password");
    /*将加密的文本写到配置文件中*/
    System.out.println("username = " + username);
    System.out.println("password = " + password);
}

得到加密后的用户名和密码。

username = aL72g6IaZDwxZE63fhujOA==
password = V+sgI2xsjCIh2gHs15jN8CyAwGzpwr6k

配置文件

password是必须自己定义的,其他都可以不配置,有默认的配置。

在敏感信息处使用对应的ENC(密文)代替

# jasypt 配置加密
jasypt:
  encryptor:
    # 密码盐值(自定义)
    password: jasypt
    # 加密算法设置
    algorithm: PBEWithMD5AndDES

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/hm_project_v4?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: ENC(aL72g6IaZDwxZE63fhujOA==)
    password: ENC(V+sgI2xsjCIh2gHs15jN8CyAwGzpwr6k)

这样就实现了对配置文件的数据进行加密或者解密了。

注意:main方法的algorithm和password 要与 配置文件的相同【重要】

获取配置文件中的数据

在配置文件中写密文,程序启动后自动解密,我们使用正常的@Value方式获取的数据即为解密后的数据。

@RestController
public class MUserController {

    @Value("${spring.datasource.password}")
    private String password;

    @GetMapping("/properties")
    public String getProperties() {
        return password;
    }
}
  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙域、白泽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值