在SpringBoot中通过jasypt进行加密解密的方法

在SpringBoot中,通过jasypt可以进行加密解密. 这个是双向的, 且可以配置密钥.

加密使用步骤
1:引入依赖

<!-- 数据库加密 -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>

测试

public class Tests {
  @Test
  public void jasyptTest() {
    BasicTextEncryptor encryptor = new BasicTextEncryptor();
    // application.properties, jasypt.encryptor.password
    encryptor.setPassword("abc");
    // encrypt root
    System.out.println(encryptor.encrypt("root"));
    System.out.println(encryptor.encrypt("root"));
    System.out.println(encryptor.encrypt("root"));
    // decrypt, the result is root
    System.out.println(encryptor.decrypt("UP/yojB7ie3apnh3mLTU7w=="));
    System.out.println(encryptor.decrypt("ik9FE3GiYLiHwchiyHg9QQ=="));
    System.out.println(encryptor.decrypt("9Obo/jq9EqmTE0QZaJFYrw=="));
  }
}

每次生成的密码是不一样的, 但是通过密钥,可以解密成一样的明文.

2.在SpringBoot中配置jasypt
配置密钥,(密钥自己指定),启动的时候需要密钥
在这里插入图片描述

jasypt.encryptor.password:abc

3:生成密文

package com.kuang;

import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class encryptorTest {
    @Autowired
    private StringEncryptor stringEncryptor;

    @Test
    public void encryptorPwd() {
         //加密
        String username = stringEncryptor.encrypt("root");
        System.out.println("加密username = " + username);
        //解密
        String username1 = stringEncryptor.decrypt(username);
        System.out.println("解密username1 = " + username1);

        String pwd = stringEncryptor.encrypt("1234");
        System.out.println("加密pwd = " + pwd);
        //解密
        String pwd1 = stringEncryptor.decrypt(pwd);
        System.out.println("解密pwd1 = " + pwd1);

    }


}

把生成的密文替换application.properties对应的账户密码
在这里插入图片描述
加上ENC()
![在这里插入图片描述](https://img-blog.csdnimg.cn/77ff0636855443aabe164e74671e1710.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAa2FuZ2Z1XzUyMQ==,size_20,color_FFFFFF,t_70,g_se,x_16

4:启动项目成功,账户密码加解密成功:

=================================================
拓展:
如果配置文件的配置密钥注释的话

#jasypt.encryptor.password=abc

启动时配置密钥

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

或者在idea配置

-Djasypt.encryptor.password=abc

在这里插入图片描述
启动成功,密码加解密完成
在这里插入图片描述

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐