java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot接口加密技巧

SpringBoot实现接口加密的五大技巧分享

作者:墨瑾轩

为了有效应对接口安全面临的挑战,接口加密作为一种至关重要的手段,能够将原始数据转化为密文进行传输,从而确保数据在传输过程中的机密性和完整性,本文将深入探讨SpringBoot接口加密的最佳实践,需要的朋友可以参考下

5大神器,让接口“秒变”加密大师

神器1:RSA+AES混合加密——加密界的“黄金CP”

目标:用RSA加密AES密钥,用AES加密数据,实现“速度与安全兼得”。

代码示例(加密工具类)

import javax.crypto.Cipher;  
import javax.crypto.spec.IvParameterSpec;  
import javax.crypto.spec.SecretKeySpec;  
import java.security.KeyFactory;  
import java.security.spec.X509EncodedKeySpec;  
import java.util.Base64;  

// 🌟 RSA工具类(服务端生成密钥对)  
public class RSAUtil {  
    private static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";  

    // 🔑 生成RSA公钥和私钥(服务端执行一次)  
    public static KeyPair generateRSAKeyPair() throws Exception {  
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");  
        generator.initialize(2048); // 推荐2048位以上  
        return generator.generateKeyPair();  
    }  

    // 🔒 用RSA公钥加密AES密钥  
    public static byte[] encryptRSA(byte[] data, PublicKey publicKey) throws Exception {  
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
        return cipher.doFinal(data);  
    }  

    // 🔓 用RSA私钥解密AES密钥  
    public static byte[] decryptRSA(byte[] encryptedData, PrivateKey privateKey) throws Exception {  
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, privateKey);  
        return cipher.doFinal(encryptedData);  
    }  
}  

// 🔐 AES工具类(对称加密)  
public class AESUtil {  
    private static final String AES_ALGORITHM = "AES/CBC/PKCS7Padding";  

    // 🔑 生成AES密钥和偏移量(客户端随机生成)  
    public static SecretKey generateAESKey() {  
        return new SecretKeySpec(KeyGenerator.getInstance("AES").generateKey().getEncoded(), "AES");  
    }  

    // 🔑 生成AES偏移量(IV)  
    public static IvParameterSpec generateIV() {  
        byte[] iv = new byte[16]; // 16字节固定长度  
        new SecureRandom().nextBytes(iv);  
        return new IvParameterSpec(iv);  
    }  

    // 🔒 AES加密数据  
    public static byte[] encryptAES(byte[] data, SecretKey key, IvParameterSpec iv) throws Exception {  
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);  
        return cipher.doFinal(data);  
    }  

    // 🔓 AES解密数据  
    public static byte[] decryptAES(byte[] encryptedData, SecretKey key, IvParameterSpec iv) throws Exception {  
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, key, iv);  
        return cipher.doFinal(encryptedData);  
    }  
}  

关键点

// 纯RSA:加密慢,且无法加密超过密钥长度的数据  
// 混合加密:RSA加密小数据(AES密钥),AES加密大数据(请求参数)  

神器2:自定义注解——给接口装个“加密开关”

目标:用注解标记需要加密的接口,实现“按需加密”。

代码示例(自定义注解)

import java.lang.annotation.*;  

// 📌 自定义@RequestRSA注解  
@Target({ElementType.TYPE, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface RequestRSA {  
    // 可扩展字段(如加密版本号)  
}  

神器3:AOP自动解密——让解密“隐形”

目标:通过AOP拦截请求,自动解密参数,无需手动处理。

代码示例(AOP切面)

import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.annotation.Around;  
import org.aspectj.lang.annotation.Aspect;  
import org.springframework.stereotype.Component;  
import com.alibaba.fastjson.JSONObject;  

@Aspect  
@Component  
public class RSAAspect {  
    @Around("@annotation(RequestRSA)")  
    public Object decryptRequest(ProceedingJoinPoint joinPoint) throws Throwable {  
        // 1️⃣ 获取原始请求参数(JSON格式)  
        Object[] args = joinPoint.getArgs();  
        String rawBody = args[0].toString(); // 假设第一个参数是请求体  

        // 2️⃣ 解析sym和asy参数  
        JSONObject bodyJson = JSONObject.parseObject(rawBody);  
        String sym = bodyJson.getString("sym"); // RSA加密的AES密钥  
        String asy = bodyJson.getString("asy"); // AES加密的请求参数  

        // 3️⃣ 解密AES密钥(使用RSA私钥)  
        byte[] encryptedAESKey = Base64.getDecoder().decode(sym);  
        byte[] decryptedAESKey = RSAUtil.decryptRSA(encryptedAESKey, getPrivateKey()); // 需实现私钥获取逻辑  

        // 4️⃣ 解密请求参数(使用AES密钥)  
        byte[] aesKey = new SecretKeySpec(decryptedAESKey, "AES"); // 转换为SecretKey  
        byte[] decryptedData = AESUtil.decryptAES(  
            Base64.getDecoder().decode(asy),  
            aesKey,  
            generateIV() // 需从参数中提取IV(此处简化)  
        );  

        // 5️⃣ 将解密后的参数绑定到接口入参对象  
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();  
        Object target = joinPoint.getTarget();  
        Method method = signature.getMethod();  
        Object[] newArgs = new Object[]{JSONObject.parseObject(new String(decryptedData), method.getParameterTypes()[0])};  

        // 6️⃣ 继续执行原方法  
        return joinPoint.proceed(newArgs);  
    }  

    // 🔑 私钥获取(需替换为实际私钥)  
    private PrivateKey getPrivateKey() {  
        // 从文件或内存中加载私钥(此处简化)  
        return null;  
    }  
}  

关键点

// 前端 → 发送 {sym: "RSA加密的AES密钥", asy: "AES加密的参数"}  
// 后端 → 自动解密 → 参数自动绑定到接口入参对象  

神器4:异常处理——让系统“防崩防炸”

目标:优雅处理解密失败场景,避免接口崩溃。

代码示例(全局异常处理)

import org.springframework.web.bind.annotation.ExceptionHandler;  
import org.springframework.web.bind.annotation.RestControllerAdvice;  

@RestControllerAdvice  
public class GlobalExceptionHandler {  
    @ExceptionHandler(Exception.class)  
    public ResponseEntity<String> handleException(Exception e) {  
        if (e.getMessage().contains("解密失败")) {  
            return ResponseEntity.status(400).body("❌ 密钥错误或请求过期!");  
        }  
        return ResponseEntity.status(500).body("内部错误!");  
    }  
}  

神器5:全流程演示——从生成密钥到调用接口

目标:实战演示如何生成密钥、加密请求、解密响应。

代码示例(全流程)

// 🚀 服务端:生成RSA密钥对  
KeyPair rsaKeyPair = RSAUtil.generateRSAKeyPair();  
PublicKey publicKey = rsaKeyPair.getPublic(); // 分发给客户端  
PrivateKey privateKey = rsaKeyPair.getPrivate(); // 服务端保存  

// 🚀 客户端:加密请求  
// 1️⃣ 生成AES密钥和偏移量  
SecretKey aesKey = AESUtil.generateAESKey();  
IvParameterSpec iv = AESUtil.generateIV();  

// 2️⃣ 加密真实参数(如JSON字符串)  
String originalParams = "{\"username\":\"张三\", \"age\":18}";  
byte[] encryptedParams = AESUtil.encryptAES(  
    originalParams.getBytes(),  
    aesKey,  
    iv  
);  

// 3️⃣ 将AES密钥和元数据用RSA加密  
JSONObject meta = new JSONObject();  
meta.put("key", Base64.getEncoder().encodeToString(aesKey.getEncoded()));  
meta.put("keyVI", Base64.getEncoder().encodeToString(iv.getIV()));  
meta.put("time", System.currentTimeMillis());  

byte[] encryptedMeta = RSAUtil.encryptRSA(  
    meta.toJSONString().getBytes(),  
    publicKey // 客户端需提前获取公钥  
);  

// 4️⃣ 发送请求  
RequestBody requestBody = new RequestBody() {  
    "sym": Base64.getEncoder().encodeToString(encryptedMeta),  
    "asy": Base64.getEncoder().encodeToString(encryptedParams)  
};  
// → 后端自动解密并返回结果  

你的接口,现在是“防破解超接口”了吗?

通过这5大神器,我们实现了:

  1. RSA+AES混合加密:速度与安全兼得,破解者“一脸懵”。
  2. 自定义@RequestRSA注解:按需加密,代码更优雅。
  3. AOP自动解密:参数自动绑定,开发者“零感知”。
  4. 全局异常处理:解密失败也能优雅报错。
  5. 全流程演示:从密钥生成到接口调用,手把手教你落地。

到此这篇关于SpringBoot实现接口加密的五大技巧分享的文章就介绍到这了,更多相关SpringBoot接口加密技巧内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文