springboot整合jasypt

本文介绍了如何在SpringBoot项目中集成Jasypt进行敏感信息加密,如数据库账号密码。通过引入jasypt-spring-boot-starter依赖,启用@EnableEncryptableProperties注解,并配置加密算法及密码,可以将明文密码转化为加密格式存储。在YAML配置文件中,使用ENC()包裹加密后的用户名和密码,确保了项目的安全性。当遇到启动报错时,可通过调整jasypt的iv-generator-classname来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值