微服务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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42469135/article/details/127265988

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签