jasypt

保证项目中的账号密码不以明文的形式展示


springboot集成jasypt

1.引入maven依赖jasypt-spring-boot-starter

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

2.启动类添加注解@EnableEncryptableProperties

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableEncryptableProperties
public class AdminMain {

    public static void main(String[] args) {
        SpringApplication.run(AdminMain.class, args);
    }
}

3.yaml文件配置

这里以配置数据库为例:

  • 配置jasypt
jasypt:
 encryptor:
   password: 02700083-9fd9-4b82-a4b4-9177e0560e92
   algorithm: PBEWithMD5AndDES
   iv-generator-classname: org.jasypt.iv.NoIvGenerator

生成账号:root,密码:mysql

import org.jasypt.util.text.BasicTextEncryptor;

/**
 *@description:
 *@author:       alex
 *@createDate:   2022/7/28 19:58
 *@version:      1.0.0
 */
public class Test {

    public static void main(String[] args) {
    	//该类的选择根据algorithm:PBEWithMD5AndDE选择的算法选择
        BasicTextEncryptor encryptor = new BasicTextEncryptor();
        encryptor.setPassword("02700083-9fd9-4b82-a4b4-9177e0560e92");
        String encrypt = encryptor.encrypt("root");
        System.out.println(encrypt);
        String decrypt = encryptor.decrypt(encrypt);
        System.out.println(decrypt);
        String encrypt = encryptor.encrypt("mysql");
        System.out.println(encrypt);
        String decrypt = encryptor.decrypt(encrypt);
        System.out.println(decrypt);
    }
}
##生成的结果,每次生成的结果都不一致
Ii5Ux7xKBVTd7+SrCkX9TQ==
root
Eg/vK2yi3/p8boYVznsyVw==
mysql
  • 配置数据库
spring:
 datasource:
   type: com.alibaba.druid.pool.DruidDataSource
   driver-class-name: com.mysql.cj.jdbc.Driver
   url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
   username: ENC(Ii5Ux7xKBVTd7+SrCkX9TQ==)
   password: ENC(Eg/vK2yi3/p8boYVznsyVw==)

总结

问题

1.如果启动项目的时候报如下错误:

Failed to bind properties under 'spring.datasource.username' to java.lang.String:

    Reason: Failed to bind properties under 'spring.datasource.username' to java.lang.String

可以通过配置yaml文件

jasypt:
  encryptor:
    iv-generator-classname: org.jasypt.iv.NoIvGenerator
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐