介绍

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;

    }

}

原文链接:https://blog.csdn.net/m0_56750901/article/details/126506258