最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Jasypt使用自定義注解+AOP實(shí)現(xiàn)敏感字段加解密

 更新時(shí)間:2025年09月29日 08:49:23   作者:Micro麥可樂  
這篇文章主要為大家詳細(xì)介紹了SpringBoot整合Jasypt使用自定義注解+AOP實(shí)現(xiàn)敏感字段加解密的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下

前言

在博主前面一篇文章中,相信小伙伴對(duì) Spring Boot 中整合 Jasypt 以及加解密的方法有了一定的了解,沒看過的小伙伴可以訪問 【Spring Boot整合Jasypt 庫實(shí)現(xiàn)配置文件和數(shù)據(jù)庫字段敏感數(shù)據(jù)的加解密】 一起探討。

本章節(jié)我們針對(duì) Jasypt 來做一些升級(jí)的玩法,使用自定義注解 + AOP 來實(shí)現(xiàn)敏感字段的加解密。

開始接入

步驟一:添加依賴

首先構(gòu)建我們的 Spring Boot 項(xiàng)目, 引入相關(guān)依賴 JasyptSpring AOP 的依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

步驟二:配置Jasypt

這里博主復(fù)用了上一篇教程的配置,如果你希望更深入的了解 YML配置和各項(xiàng)配置的說明,可以訪問

【Spring Boot整合Jasypt 庫實(shí)現(xiàn)配置文件和數(shù)據(jù)庫字段敏感數(shù)據(jù)的加解密】

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableEncryptableProperties
public class StringEncryptorConfig {
    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword("password");
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }
}

步驟三:創(chuàng)建自定義注解

接下來,我們創(chuàng)建兩個(gè)自定義注解,用于標(biāo)記需要加解密的字段以及方法

舉個(gè)例子

  • 前端傳遞后端某些值需要加密入庫 (需要方法注解是加密)
  • 后端返回前端某些值需要解密顯示 (需要方法注解是解密)

定義一個(gè)作用在字段的注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JasyptField {
}

定義一個(gè)作用在方法上的注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JasyptMethod {
    String value() default "ENC"; //ENC:加密 DEC:解密
}

步驟四:創(chuàng)建AOP切面

創(chuàng)建一個(gè)AOP切面,主要思路是找到方法上標(biāo)注了 JasyptMethod 注解且定義枚舉類型是加密還是解密,獲取到對(duì)應(yīng)參數(shù) joinPoint.getArgs() 在進(jìn)行加密或是獲取返回對(duì)象解密,無論加密解密最后調(diào)用 proceed(Object[] args) 方法改變值

需要注意處理的問題

1、獲取參數(shù)如果是字符串,直接加密字符串

2、獲取參數(shù)是對(duì)象,則通過反射獲取對(duì)象字段上@JasyptField注解的字段進(jìn)行加密;

3、獲取參數(shù)是集合,需要循環(huán)上一步驟操作

4、解密返回對(duì)象 同樣需要處理字符串 、對(duì)象 、集合操作

注意看代碼解釋!注意看代碼解釋!注意看代碼解釋!

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

@Aspect
@Component
@Slf4j
public class JasyptAspect {

    //注入加密類
    private final StringEncryptor stringEncryptor;

    // jasyptStringEncryptor 配置類中定義的名稱
    public JasyptAspect(@Qualifier("jasyptStringEncryptor") StringEncryptor stringEncryptor) {
        this.stringEncryptor = stringEncryptor;
    }


    @Pointcut("@annotation(JasyptMethod)")
    public void pointCut() {
    }


    @SneakyThrows
    @Around("pointCut())")
    public Object jasyptAround(ProceedingJoinPoint joinPoint) {
        Object proceed;
        //獲取注解類
        JasyptMethod jasyptMethod = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(JasyptMethod.class);
        //獲取注解傳遞值
        String value = jasyptMethod.value();
        //獲取參數(shù)
        Object[] args = joinPoint.getArgs();
        // 這里可以定義常量或枚舉判斷,博主就直接判斷了
        if(value.equals("ENC")){
            for(int i=0 ; i < args.length ; i++){
                // 判斷字符串還是對(duì)象
                if(args[i] instanceof String) {
                    args[i] = stringEncryptor.encrypt(String.valueOf(args[i]));
                }else {
                    //對(duì)象 還分集合還是單個(gè)對(duì)象
                    boolean isList = (args[i] instanceof List<?>);
                    handlerArgs(args[i], value, isList);
                }
            }
            proceed = joinPoint.proceed(args);
        }else{
            proceed = joinPoint.proceed();
            // 判斷字符串還是對(duì)象
            if(proceed instanceof String) {
                proceed = stringEncryptor.decrypt(String.valueOf(proceed));
            }else {
                //對(duì)象 還分集合還是單個(gè)對(duì)象
                boolean isList = (proceed instanceof List<?>);
                handlerArgs(proceed, value, isList);
            }
        }
        return proceed;
    }

    /**
     * 處理對(duì)象加解密
     * @param obj 參數(shù)對(duì)象
     * @param value 加解密值
     * @param isList 是否集合
     */
    private void handlerArgs(Object obj , String value , boolean isList){
        if(isList){
            List<Object> objs = (List<Object>)obj;
            for(Object o : objs){
                handlerFields(o, value);
            }
        }else{
            handlerFields(obj, value);
        }
    }

    /**
     * 抽取公共處理字段加解密方法
     * @param obj
     * @param value
     */
    private void handlerFields(Object obj , String value){
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field : fields){
            //判斷是否存在注解
            boolean hasJasyptField = field.isAnnotationPresent(JasyptField.class);
            if (hasJasyptField) {
                try {
                    field.setAccessible(true);
                    String plaintextValue = null;
                    plaintextValue = (String)field.get(obj);
                    String handlerValue;
                    if(value.equals("ENC")){
                        handlerValue = stringEncryptor.encrypt(plaintextValue); //處理加密
                    }
                    else{
                        handlerValue = stringEncryptor.decrypt(plaintextValue); //處理解密
                    }
                    field.set(obj, handlerValue);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

步驟四:創(chuàng)建示例實(shí)體類

模擬一個(gè)User類,包含需要加密的字段,并使用 @JasyptField 注解標(biāo)記

import lombok.Data;

@Data
public class UserDto {

    @JasyptField
    private String phone;

    @JasyptField
    private String idCard;

    private int age;
}

步驟五:創(chuàng)建測(cè)試Controller

創(chuàng)建一個(gè) Controller ,用于處理用戶請(qǐng)求,主要模擬保存單個(gè)對(duì)象、集合對(duì)象,以及返回單個(gè)對(duì)象、集合對(duì)象的操作

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api")
@Slf4j
public class JasyptController {

    /**
     * 參數(shù)是字符串
     * @param text
     * @return
     */
    @RequestMapping("/param-text")
    @JasyptMethod
    public String isStringParam(String text){
        log.info("參數(shù)是字符串: {}" ,  text);
        return text;
    }

    /**
     * 參數(shù)是 單個(gè)對(duì)象
     * @param userDto
     * @return
     */
    @RequestMapping("/insert-user")
    @JasyptMethod
    public UserDto insertUser(@RequestBody UserDto userDto){
        log.info("參數(shù)是對(duì)象: {}" , userDto.toString());
        //TODO 操縱入庫
        return userDto;
    }

    /**
     * 參數(shù)是 集合對(duì)象
     * @param userDtos
     * @return
     */
    @RequestMapping("/insert-users")
    @JasyptMethod
    public List<UserDto> insertUsers(@RequestBody List<UserDto> userDtos){
        log.info("參數(shù)是集合: {}", userDtos.toString());
        //TODO 操縱入庫
        return userDtos;
    }
    
    /**
     * 返回是對(duì)象
     * @return
     */
    @RequestMapping("/get-user")
    @JasyptMethod("DEC")
    public UserDto getUser(){
        //模擬數(shù)據(jù)庫取出
        UserDto userDto = new UserDto();
        userDto.setAge(10);
        userDto.setPhone("WyXyMRDDdvZEri1XcsPyMA/Pxv+f/N9ODU612IXi4HazSK5NicKK+zZJKolEz8bv");
        userDto.setIdCard("/KP3oTWB4pDRyyio54fJ+634pIS7VyVxltNACLG/gtDof4UDYTICMd+zsimbHGDJ0JwiubTLhHqMNxztyAU7zg==");
        return userDto;
    }

    /**
     * 返回是集合對(duì)象
     * @return
     */
    @RequestMapping("/get-users")
    @JasyptMethod("DEC")
    public List<UserDto> getUsers(){
        //模擬數(shù)據(jù)庫取出
        UserDto userDto = new UserDto();
        userDto.setAge(10);
        userDto.setPhone("WyXyMRDDdvZEri1XcsPyMA/Pxv+f/N9ODU612IXi4HazSK5NicKK+zZJKolEz8bv");
        userDto.setIdCard("/KP3oTWB4pDRyyio54fJ+634pIS7VyVxltNACLG/gtDof4UDYTICMd+zsimbHGDJ0JwiubTLhHqMNxztyAU7zg==");

        UserDto userDto2 = new UserDto();
        userDto2.setAge(100);
        userDto2.setPhone("WyXyMRDDdvZEri1XcsPyMA/Pxv+f/N9ODU612IXi4HazSK5NicKK+zZJKolEz8bv");
        userDto2.setIdCard("/KP3oTWB4pDRyyio54fJ+634pIS7VyVxltNACLG/gtDof4UDYTICMd+zsimbHGDJ0JwiubTLhHqMNxztyAU7zg==");

        List<UserDto> userDtos = new ArrayList<>();
        userDtos.add(userDto);
        userDtos.add(userDto2);
        return userDtos;
    }
}

步驟六:驗(yàn)證功能

運(yùn)行 Spring Boot 應(yīng)用程序,并發(fā)送請(qǐng)求到接口。觀察請(qǐng)求和響應(yīng)中的數(shù)據(jù),確保密碼字段已被加密

加密參數(shù)是字符串

加密參數(shù)是對(duì)象

加密參數(shù)是集合

解密返回是對(duì)象

解密返回是集合

至此,我們所有測(cè)試均已通過,小伙伴們可以復(fù)制博主的代碼進(jìn)行測(cè)試,編寫的代碼結(jié)構(gòu)如下(僅為了演示,所有類都放在一個(gè)包下)

結(jié)語

通過本文的步驟,我們成功地在Spring Boot項(xiàng)目中整合了Jasypt,并使用自定義注解結(jié)合AOP實(shí)現(xiàn)了敏感字段的自動(dòng)加解密。這種方法不僅提高了代碼的可讀性和可維護(hù)性,還增強(qiáng)了數(shù)據(jù)的安全性。在實(shí)際項(xiàng)目中,您可以進(jìn)一步擴(kuò)展和優(yōu)化這個(gè)示例(比如數(shù)據(jù)入庫、數(shù)據(jù)查詢等),以適應(yīng)更多復(fù)雜的需求。

到此這篇關(guān)于SpringBoot整合Jasypt使用自定義注解+AOP實(shí)現(xiàn)敏感字段加解密的文章就介紹到這了,更多相關(guān)SpringBoot Jasypt加解密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 深入理解Java中的final關(guān)鍵字_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    深入理解Java中的final關(guān)鍵字_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理

    Java中的final關(guān)鍵字非常重要,它可以應(yīng)用于類、方法以及變量。這篇文章中我將帶你看看什么是final關(guān)鍵字以及使用final的好處,具體內(nèi)容詳情通過本文學(xué)習(xí)吧
    2017-04-04
  • 配置SpringBoot方便的切換jar和war的方法示例

    配置SpringBoot方便的切換jar和war的方法示例

    這篇文章主要介紹了配置SpringBoot方便的切換jar和war的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-01-01
  • MyBatis?Generator生成數(shù)據(jù)庫模型實(shí)現(xiàn)示例

    MyBatis?Generator生成數(shù)據(jù)庫模型實(shí)現(xiàn)示例

    這篇文章主要為大家介紹了MyBatis?Generator生成數(shù)據(jù)庫模型實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • java編程實(shí)現(xiàn)求質(zhì)數(shù)與因式分解代碼分享

    java編程實(shí)現(xiàn)求質(zhì)數(shù)與因式分解代碼分享

    這篇文章主要介紹了Java編程實(shí)現(xiàn)求質(zhì)數(shù)與因式分解代碼分享,對(duì)二者的概念作了簡(jiǎn)單介紹(多此一舉,哈哈),都是小學(xué)數(shù)學(xué)老師的任務(wù),然后分享了求解質(zhì)數(shù)和因式分解的Java代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • Java之操作Redis案例講解

    Java之操作Redis案例講解

    這篇文章主要介紹了Java之操作Redis案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • SpringBoot集成iTextPDF的實(shí)例

    SpringBoot集成iTextPDF的實(shí)例

    SpringBoot集成iTextPDF時(shí),創(chuàng)建PDF文檔涉及Document、PdfPTable和PdfPCell對(duì)象,設(shè)置文檔大小和頁邊距,使用Paragraph設(shè)置段落樣式,并通過Table和Cell控制表格樣式和對(duì)齊,還可加入圖片美化文檔,這些步驟對(duì)于生成具有中文內(nèi)容的PDF文件至關(guān)重要
    2024-09-09
  • Java Stream 并行流簡(jiǎn)介、使用與注意事項(xiàng)小結(jié)

    Java Stream 并行流簡(jiǎn)介、使用與注意事項(xiàng)小結(jié)

    Java8并行流基于Stream API,利用多核CPU提升計(jì)算密集型任務(wù)效率,但需注意線程安全、順序不確定及線程池管理,可通過自定義線程池與CompletableFuture結(jié)合實(shí)現(xiàn)更靈活的異步處理,本文給大家介紹Java Stream并行流簡(jiǎn)介、使用與注意事項(xiàng)小結(jié),感興趣的朋友一起看看吧
    2025-08-08
  • SpringBoot 統(tǒng)一異常處理詳解

    SpringBoot 統(tǒng)一異常處理詳解

    這篇文章主要介紹了SpringBoot統(tǒng)一異常處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Spring AOP實(shí)現(xiàn)原理解析

    Spring AOP實(shí)現(xiàn)原理解析

    這篇文章主要為大家詳細(xì)介紹了Spring AOP的實(shí)現(xiàn)原理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • springboot響應(yīng)json?null值過濾方式

    springboot響應(yīng)json?null值過濾方式

    這篇文章主要介紹了springboot響應(yīng)json?null值過濾方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11

最新評(píng)論

墨竹工卡县| 正宁县| 梁平县| 广宗县| 突泉县| 师宗县| 永修县| 平原县| 定远县| 卢氏县| 米泉市| 台南市| 辽中县| 金堂县| 津南区| 绥阳县| 津南区| 福海县| 固原市| 双鸭山市| 炉霍县| 津市市| 中卫市| 许昌市| 新余市| 沂源县| 周至县| 高邮市| 鹤峰县| 和田县| 汝城县| 仲巴县| 绥德县| 玉环县| 胶南市| 乌兰浩特市| 岢岚县| 渝北区| 江城| 松桃| 彩票|