微服务SpringBoot整合Jasypt加密工具

这篇具有很好参考价值的文章主要介绍了微服务SpringBoot整合Jasypt加密工具。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

springboot jasypt,微服务,spring boot,微服务,java,加密工具,加密算法

一、Jasypt介绍

Jasypt是Java加密工具包,能支持对密码的哈希加密,对文本和二进制数据的对称加解密,还能集成SpringBoot项目对配置文件中的密钥进行加密存储。

引入依赖如下:

<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>

二、Jasypt手动使用

2.1 密码加密场景

用户注册账户的时候需要输入密码,我们将密码加密后保存到数据库中,保证用户的敏感数据的安全性。当用户再次登录的时候,我们需要将登录密码和注册时保存的密文密码进行比对,只有比对一致才能完成登录。

密码加密工具类主要有三个,它们都是实现了PasswordEncryptor接口,下面我们逐步来看。

@Slf4j
@RestController
public class SignController {

    private final BasicPasswordEncryptor basicPasswordEncryptor = new BasicPasswordEncryptor();

    private String encryptedPassword = null;

    @GetMapping("/signup/{password}")
    public String signup(@PathVariable String password){
        log.info("用户注册密码为:{}", password);
        encryptedPassword = basicPasswordEncryptor.encryptPassword(password);
        log.info("用户注册密码加密后为:{}", encryptedPassword);
        return encryptedPassword;
    }

    @GetMapping("/signin/{password}")
    public String signin(@PathVariable String password){
        log.info("用户登录密码为:{}", password);
        if(basicPasswordEncryptor.checkPassword(password, encryptedPassword)){
            log.info("用户登录成功!");
            return "success";
        }
        log.info("用户登录失败!");
        return "fail";
    }

}

启动项目后,我们首先注册用户密码localhost:8080/signup/123456,就能得到密文5b32ygn5pbBvphjIKco6X8Z2VfWqwEUw,并将其保存到类变量中暂存,当我们再次登录localhost:8080/signin/123456,就能登录成功了。相反的,如果登录时密码随意输错,就会登录失败。

2022-10-11 15:41:57.038  INFO 26268 --- [nio-8080-exec-1] c.e.myapp.controller.SignController      : 用户注册密码为:123456
2022-10-11 15:41:57.039  INFO 26268 --- [nio-8080-exec-1] c.e.myapp.controller.SignController      : 用户注册密码加密后为:5b32ygn5pbBvphjIKco6X8Z2VfWqwEUw
2022-10-11 15:42:07.405  INFO 26268 --- [nio-8080-exec-3] c.e.myapp.controller.SignController      : 用户登录密码为:123456
2022-10-11 15:42:07.406  INFO 26268 --- [nio-8080-exec-3] c.e.myapp.controller.SignController      : 用户登录成功!
2022-10-11 15:42:12.767  INFO 26268 --- [nio-8080-exec-4] c.e.myapp.controller.SignController      : 用户登录密码为:123457
2022-10-11 15:42:12.767  INFO 26268 --- [nio-8080-exec-4] c.e.myapp.controller.SignController      : 用户登录失败!

那么这种加密方式是什么呢?我们可以打开BasicPasswordEncryptor的源码,看到类上面的注释:

  • Algorithm: MD5.
  • Salt size: 8 bytes.
  • Iterations: 1000.

意思就是使用的MD5这种哈希算法,并且使用8字节(64位)的盐值,迭代计算1000次得到的密文。

除了使用如上的BasicPasswordEncryptor工具之外,还有StrongPasswordEncryptor工具类,它的加密登记更加的安全:

  • Algorithm: SHA-256.
  • Salt size: 16 bytes.
  • Iterations: 100000.

如果这些加密算法都不能满足你的要求,就可以使用ConfigurablePasswordEncryptor来自定义加密工具类ConfigurablePasswordEncryptor,可以设置自己需要使用的算法。

总结:

接口类PasswordEncryptor主要有如下三个实现类:

  • BasicPasswordEncryptor,使用MD5算法;
  • StrongPasswordEncryptor,使用SHA-256算法;
  • ConfigurablePasswordEncryptor,可自定义指定哈希算法;

哈希算法是不可逆的,因此只有加密encryptPassword和检查checkPassword两个方法。

2.2 文本加密场景

用户的手机号、身份证号等敏感信息在存储的时候需要进行加密,但是这些敏感数据在需要使用的时候是需要明文解密的,因此不适合使用2.1节的哈希算法,而是使用对称加密的形式。

文本加密工具类主要有三个,它们都是实现了TextEncryptor接口,下面我们逐步来看。

@Slf4j
@RestController
public class TextController {

    private static final BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
    private static final String SECRET = "hello";
    private String encryptedText = null;

    static {
        basicTextEncryptor.setPassword(SECRET);
    }

    @GetMapping("/encryptText/{plainText}")
    public String encryptText(@PathVariable String plainText){
        log.info("用户输入明文:{}", plainText);
        encryptedText = basicTextEncryptor.encrypt(plainText);
        log.info("用户加密密文:{}", encryptedText);
        return encryptedText;
    }

    @GetMapping("/decryptText")
    public String decryptText(){
        String plainText = basicTextEncryptor.decrypt(encryptedText);
        log.info("用户原始明文:{}", plainText);
        return plainText;
    }

}

项目启动后,我们分别访问localhost:8080/encryptText/hello进行加密,访问localhost:8080/decryptText进行解密。

2022-10-11 15:52:36.949  INFO 21652 --- [nio-8080-exec-1] c.e.myapp.controller.TextController      : 用户输入明文:hello
2022-10-11 15:52:36.950  INFO 21652 --- [nio-8080-exec-1] c.e.myapp.controller.TextController      : 用户加密密文:u/qYluhyFpyOA6xMD3z3JA==
2022-10-11 15:52:46.345  INFO 21652 --- [nio-8080-exec-2] c.e.myapp.controller.TextController      : 用户原始明文:hello

我们同样打开BasicTextEncryptor可以看到它的加密原理:

  • Algorithm: PBEWithMD5AndDES.
  • Key obtention iterations: 1000.

同样的,我们可以使用安全性更高的StrongTextEncryptor

  • Algorithm: PBEWithMD5AndTripleDES.
  • Key obtention iterations: 1000.

还有安全性更高的AES256TextEncryptor

  • Algorithm: PBEWithHMACSHA512AndAES_256".
  • Key obtention iterations: 1000.

2.3 数值加密场景

如果需要对整数或者小数进行加密,就可以分别使用IntegerNumberEncryptor接口和DecimalNumberEncryptor接口的实现类。同样的,这种场景的加密也都是对称加密,用法完全一样。

IntegerNumberEncryptor:主要用来对整数进行加解密。

  • BasicIntegerNumberEncryptor
    • Algorithm: PBEWithMD5AndDES.
    • Key obtention iterations: 1000.
  • StrongIntegerNumberEncryptor
    • Algorithm: PBEWithMD5AndTripleDES.
    • Key obtention iterations: 1000.
  • AES256IntegerNumberEncryptor
    • Algorithm: PBEWithHMACSHA512AndAES_256.
    • Key obtention iterations: 1000.

DecimalNumberEncryptor:主要用来对小数进行加解密。

  • BasicDecimalNumberEncryptor
    • Algorithm: PBEWithMD5AndDES.
    • Key obtention iterations: 1000.
  • StrongDecimalNumberEncryptor
    • Algorithm: PBEWithMD5AndTripleDES.
    • Key obtention iterations: 1000.
  • AES256DecimalNumberEncryptor
    • Algorithm: PBEWithHMACSHA512AndAES_256.
    • Key obtention iterations: 1000.

2.4 二进制数据加密场景

暂未遇到需要加密二进制数据的业务场景,此处略过,使用方法可以参考官网。

三、Jasypt整合SpringBoot

SpringBoot应用中有很多密钥和密码都是存储在配置文件中的,我们需要将它们以密文的方式存储起来。

# 服务器配置
server:
  port: 8080

# Spring配置
spring:
  # 数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&&serverTimezone=Asia/Shanghai&&useSSL=false
    username: root
    # 此处是密码的密文,要用ENC()进行包裹
    password: ENC(KZeGx0ixuy4UrBp1HuhiDNnKB0cJr0cW)

# mybatis配置
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml

# 加密配置
jasypt:
  encryptor:
    # 指定加密密钥,生产环境请放到启动参数里面
    password: your-secret
    # 指定解密算法,需要和加密时使用的算法一致
    algorithm: PBEWithMD5AndDES
    # 指定initialization vector类型
    iv-generator-classname: org.jasypt.iv.NoIvGenerator

如上是对数据库密码进行加密存储,密文是怎么的来的?可以写一个测试类,使用第二节介绍的内容自己手动加密。

@Slf4j
public final class JasyptUtils {
    /**
     * 加密使用密钥
     */
    private static final String PRIVATE_KEY = "lybgeek";

    private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

    static {
        basicTextEncryptor.setPassword(PRIVATE_KEY);
    }

    /**
     * 私有构造方法,防止被意外实例化
     */
    private JasyptUtils() {
    }

    /**
     * 明文加密
     *
     * @param plaintext 明文
     * @return String
     */
    public static String encrypt(String plaintext) {
        log.info("明文字符串为:{}", plaintext);
        // 使用的加密算法参考2.2节内容,也可以在源码的类注释中看到
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        log.info("密文字符串为:{}", ciphertext);
        return ciphertext;
    }

    /**
     * 解密
     *
     * @param ciphertext 密文
     * @return String
     */
    public static String decrypt(String ciphertext) {
        log.info("密文字符串为:{}", ciphertext);
        ciphertext = "ENC(" + ciphertext + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
            log.info("明文字符串为:{}", plaintext);
            return plaintext;
        }
        log.error("解密失败!");
        return "";
    }
}
@Slf4j
public class JasyptUtilsTest {

    @Test
    public void testEncrypt(){
        String plainText = "Glrs@1234";
        String ciperText = JasyptUtils.encrypt(plainText);
        log.info("加密后的密文为:{}", ciperText);
    }

    @Test
    public void testDecrypt(){
        String ciperText = "KZeGx0ixuy4UrBp1HuhiDNnKB0cJr0cW";
        String plainText = JasyptUtils.decrypt(ciperText);
        log.info("解密后的明文为:{}", plainText);
    }

}

经过如上的配置,启动项目,如下从数据库获取数据的应用逻辑就能正常使用了。

@Slf4j
@RestController
public class HelloController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/getHello")
    public String getHello(){
        log.info("myapp works!");
        List<User> users = userMapper.listUsers();
        return users.toString();
    }

}
@Mapper
public interface UserMapper {
    List<User> listUsers();
}
<mapper namespace="com.example.myapp.mapper.UserMapper">
    <select id="listUsers" resultType="com.example.myapp.bean.User">
        select zu.user_id userId, zu.user_name userName, zu.age age, zu.user_email userEmail from zx_user zu;
    </select>
</mapper>

四、生成环境启动

生产环境密钥作为启动参数:

java -jar -Djasypt.encryptor.password=your-secret

无、参考文档

Jasypt: Java simplified encryption - Jasypt: Java simplified encryption - Main文章来源地址https://www.toymoban.com/news/detail-783564.html

到了这里,关于微服务SpringBoot整合Jasypt加密工具的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微服务nacos或者yml配置内容部分加密jasypt

    1.引入依赖(版本自定): 2.yml新增配置: 注:algorithm是加密算法,官方默认的加密算法是 PBEWITHHMACSHA512ANDAES_256,但是如果你用的是 JDK1.8,还用不了这个算法,JDK9以上才支持,所以可以把这个算法改成PBEWithMD5AndDES。 2.1.2版本默认加密方式为:PBEWithMD5AndDES 3.0.3版本默认加密

    2024年02月10日
    浏览(22)
  • Spring Boot项目使用 jasypt 加密组件进行加密(例如:数据库、服务的Key、等等进行加密)

    🍓 简介:java系列技术分享(👉持续更新中…🔥) 🍓 初衷:一起学习、一起进步、坚持不懈 🍓 如果文章内容有误与您的想法不一致,欢迎大家在评论区指正🙏 🍓 希望这篇文章对你有所帮助,欢迎点赞 👍 收藏 ⭐留言 📝 🍓 更多文章请点击 密码配置项都不加密? 想啥呢? 一

    2024年02月07日
    浏览(41)
  • 【Jasypt】Spring Boot 配置文件加解密 Jasypt 配置文件加密

    Jasypt是一个Java简易加密库,用于加密配置文件中的敏感信息,如数据库密码。jasypt库与springboot集成,在实际开发中非常方便。 1、Jasypt Spring Boot 为 spring boot 应用程序中的属性源提供加密支持,出于安全考虑,Spring boot 配置文件中的敏感信息通常需要对它进行加密/脱敏处理,

    2024年02月03日
    浏览(32)
  • jasypt加密解密

    1. 导入依赖 2. yml配置 导入依赖后,就可以进行jasypt的加密配置 进行完上面操作,就可以在需要加密的地方进行配置了。 比如,配置数据库的账号密码,使用格式 ENC(加密后的密码) 进行加密。 但是如何获取这些加密值呢?接下来写一个加密解密的工具类。 3. 加密解密工具类

    2024年02月11日
    浏览(36)
  • SpringBoot【集成 jasypt】实现配置信息自定义加解密(自定义的属性探测和密码解析器)

    Jasypt是一个Java简易加密库,用于加密配置文件中的敏感信息,如数据库密码。它可以帮助开发人员在应用程序中加密密码、敏感信息和数据通信,还包括高安全性、基于标准的加密技术、可同时单向和双向加密的加密密码、文本、数字和二进制文件。如果您正在使用Spring B

    2024年02月05日
    浏览(33)
  • 加密组件Jasypt学习、实战及踩坑记录

    最近入职新公司,因几乎全部项目都使用到jasypt,故而初步学习记录下本文(持续更新)。 官网及GitHub给出的简介:使用简单,性能好,特性features非常丰富;支持 另,有个开源Jasypt-spring-boot组件,GitHub,集成Jasypt,方便Spring Boot开发者使用。 开发中最常见的场景就是对数据

    2023年04月16日
    浏览(32)
  • Spring Boot使用jasypt处理数据库账号密码等数据加密问题

    在我们业务场景中,项目中的application.yml 配置文件比如数据库账号密码,的各种链接的username,password的值都是明文的,存在一定的安全隐患,可以使用jasypt 加密框架的方式进行明文加密,进而使得我们项目更加安全 注意这里排除了mybatis-plus的包可能是项目中有冲突依赖,

    2024年02月06日
    浏览(42)
  • jasypt-spring-boot敏感信息加密解密利器使用指南

    Springboot 整合Jasypt,实现配置信息的安全,如数据库连接.账号和密码.接口凭证信息等。 Jasypt可以为Springboot加密的信息很多,主要有: System Property 系统变量 Envirnment Property 环境变量 Command Line argument 命令行参数 Application.properties 应用配置文件 Yaml properties 应用配置文件 other

    2024年02月03日
    浏览(38)
  • Spring Boot学习随笔- Jasypt加密数据库用户名和密码以及解密

    学习视频:【编程不良人】2021年SpringBoot最新最全教程 Jasypt 全称是Java Simplified Encryption,是一个开源项目。 Jasypt与Spring Boot集成,以便在应用程序的属性文件中加密敏感信息,然后在应用程序运行时解密这些信息。 可以使用 jasypt-spring-boot-starter 这个依赖项。从而实现属性源

    2024年02月04日
    浏览(54)
  • 在Spring Boot微服务使用jasypt-spring-boot加密和解密yml配置文件

    记录 :424 场景 :在Spring Boot微服务,使用jasypt-spring-boot加密和解密yml配置文件中的配置信息。 版本 :JDK 1.8,Spring Boot 2.6.3,jasypt-1.9.3,jasypt-spring-boot-2.1.2, jasypt-spring-boot-3.0.5。 开源地址 :https://github.com/ulisesbocchio/jasypt-spring-boot 1.在Spring Boot微服务使用jasypt-spring-boot-3.0.5版本

    2024年02月09日
    浏览(59)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包