讓數(shù)據(jù)傳輸更優(yōu)雅:SpringBoot前后端加密技巧全攻略
在Web應(yīng)用中,確保前后端之間的數(shù)據(jù)傳輸安全是非常重要的。這通常涉及到使用HTTPS協(xié)議、數(shù)據(jù)加密、令牌驗(yàn)證等安全措施。本文通過將前后端之間的傳輸數(shù)據(jù)進(jìn)行加密,用于在Spring Boot應(yīng)用中實(shí)現(xiàn)前后端傳輸加密設(shè)計(jì)。
一、數(shù)據(jù)加密方案
即使使用了HTTPS,也可能需要在應(yīng)用層對數(shù)據(jù)進(jìn)行額外的加密。這可以通過以下方式實(shí)現(xiàn):
對稱加密: 加密解密是同一個(gè)密鑰,速度快,數(shù)據(jù)接收方需要公布其私鑰給數(shù)據(jù)傳輸方進(jìn)行數(shù)據(jù)加密,安全性完全依賴于該密鑰。適合做大量數(shù)據(jù)或數(shù)據(jù)文件的加解密。
- 使用AES、DES等對稱加密算法對敏感數(shù)據(jù)進(jìn)行加密和解密。
- 前后端需要共享一個(gè)密鑰(key)用于加密和解密。
- 密鑰的管理和傳輸需要特別注意安全性。
非對稱加密: 加密用公鑰,解密用私鑰。公鑰和私鑰是成對的(可借助工具生成,如openssl等),即用公鑰加密的數(shù)據(jù),一定能用其對應(yīng)的私鑰解密,能用私鑰解密的數(shù)據(jù),一定是其對應(yīng)的公鑰加密。對大量數(shù)據(jù)或數(shù)據(jù)文件加解密時(shí),效率較低。數(shù)據(jù)接收方需公布其公鑰給數(shù)據(jù)傳輸方,私鑰自己保留,安全性更高。
- 使用RSA、ECC等非對稱加密算法。
- 私鑰用于加密數(shù)據(jù),公鑰用于解密數(shù)據(jù)。
- 公鑰可以公開,而私鑰需要安全存儲。
混合加密
- 結(jié)合使用對稱加密和非對稱加密。
- 使用非對稱加密算法交換對稱加密的密鑰(會話密鑰),然后使用會話密鑰進(jìn)行實(shí)際的數(shù)據(jù)加密和解密。
這里就贅述介紹每種加密的實(shí)現(xiàn)方式和原理。
1.1 數(shù)據(jù)加密實(shí)現(xiàn)方式
- 如果數(shù)據(jù)傳輸較大,密鑰不需要進(jìn)行網(wǎng)絡(luò)傳輸,數(shù)據(jù)不需要很高的安全級別,則采用對稱加密,只要能保證密鑰沒有人為外泄即可;
- 如果數(shù)據(jù)傳輸小,而且對安全級別要求高,或者密鑰需要通過internet交換,則采用非對稱加密;
本文采用了兩者結(jié)合的方式(混合加密模式),這樣是大多數(shù)場景下采用的加密方式。加密時(shí)序圖如下所示:
圖片
通過使用對稱加密(AES) 和 非對稱加密(RSA) 的方式來實(shí)現(xiàn)對數(shù)據(jù)的加密;即通過對稱加密進(jìn)行業(yè)務(wù)數(shù)據(jù)體的加密,通過非對稱加密進(jìn)行對稱加密密鑰的加密; 它結(jié)合了對稱加密的高效性 和 非對稱加密的安全性。
注意事項(xiàng):
- 確保RSA公鑰在傳輸過程中是安全的,因?yàn)槿魏螕碛羞@個(gè)公鑰的人都可以用它來加密AES密鑰,但只有擁有私鑰的人才能解密它。
- 確保在加密和解密過程中使用安全的加密庫和最新的加密算法標(biāo)準(zhǔn)。
- 定期更換密鑰對和對稱密鑰,以降低密鑰泄露的風(fēng)險(xiǎn)。
這種混合加密模式提供了安全性和效率之間的平衡。對稱加密(如AES)用于加密大量數(shù)據(jù),因?yàn)樗ǔ1确菍ΨQ加密更快。而非對稱加密(如RSA)用于加密密鑰,因?yàn)樗峁┝烁鼜?qiáng)的安全性,特別是當(dāng)密鑰需要在不安全的通道上傳輸時(shí)。
1.2 AES加密工具類創(chuàng)建
封裝AESUtil工具類時(shí) pom.xml 中運(yùn)用到的依賴:
<!-- hutool-all工具類依賴 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
AES加解密工具類 AESUtil 代碼:
package com.example.api_security_demo.utils;
import cn.hutool.core.codec.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
/**
* @ClassName : AESUtil
* @Description : AES加密工具類
* @Author : AD
*/
public class AESUtil {
public static final String CHAR_ENCODING = "UTF-8";
/**
* [常見算法]AES、DES、RSA、Blowfish、RC4 等等
* [常見的模式] ECB (電子密碼本模式)、CBC (密碼分組鏈接模式)、CTR (計(jì)數(shù)模式) 等等
* [常見的填充] NoPadding、PKCS5Padding、PKCS7Padding 等等
*
* [AES算法]可以有以下幾種常見的值:
* AES:標(biāo)準(zhǔn)的AES算法。
* AES/CBC/PKCS5Padding:使用CBC模式和PKCS5填充的AES算法。
* AES/ECB/PKCS5Padding:使用ECB模式和PKCS5填充的AES算法。
* AES/GCM/NoPadding:使用GCM模式的AES算法,不需要填充。
* AES/CCM/NoPadding:使用CCM模式的AES算法,不需要填充。
* AES/CFB/NoPadding:使用CFB模式的AES算法,不需要填充。
* */
public static final String AES_ALGORITHM = "AES";
public static char[] HEXCHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Description: 隨機(jī)生成 AESKey密鑰
*
* @param length 隨機(jī)生成密鑰長度
* @return java.lang.String
*/
public static String getAESKey(int length) throws Exception
{
/*
* Random類用于生成偽隨機(jī)數(shù)。
* */
Random random = new Random();
StringBuilder ret = new StringBuilder();
for(int i = 0; i < length; i++)
{
// 選擇生成數(shù)字還是字符
boolean isChar = (random.nextInt(2) % 2 == 0);
/* 0隨機(jī)生成一個(gè)字符*/
if (isChar)
{
// 選擇生成大寫字母 / 小寫字母
int choice = (random.nextInt(2) % 2 == 0) ? 65 : 97;
ret.append((char) (choice+random.nextInt(26)));
/* 1隨機(jī)生成一個(gè)數(shù)字 */
}else
{
ret.append( random.nextInt(10));
}
}
return ret.toString();
}
/**
* Description: 加密
*
* @param data 待加密數(shù)據(jù)內(nèi)容
* @param aesKey 加密密鑰
* @return byte[]
*/
public static byte[] encrypt(byte[] data,byte[] aesKey)
{
if (aesKey.length != 16)
{
throw new RuntimeException("Invalid AES key length (must be 16 bytes) !");
}
try{
/*
* 創(chuàng)建一個(gè)SecretKeySpec對象來包裝AES密鑰。
* 它使用了aesKey字節(jié)數(shù)組作為密鑰,并指定算法為"AES"。
* 這個(gè)對象用來提供對稱加密算法的密鑰。
* */
SecretKeySpec secretKey = new SecretKeySpec(aesKey, "AES");
/*
* 獲取SecretKeySpec對象中的編碼形式,將其存儲在encodedFormat字節(jié)數(shù)組中。
* 這個(gè)編碼形式可以被用來重新構(gòu)造密鑰。
* */
byte[] encodedFormat = secretKey.getEncoded();
/*
* 使用encodedFormat字節(jié)數(shù)組創(chuàng)建了另一個(gè)SecretKeySpec對象secKey。
* 這個(gè)對象也用來提供對稱加密算法的密鑰。
* */
SecretKeySpec secKey = new SecretKeySpec(encodedFormat, "AES");
/*
* 使用Cipher類的getInstance()方法獲取了一個(gè)Cipher對象(創(chuàng)建密碼器)。
* 這個(gè)對象用來完成加密或解密的工作。
* */
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
/*
* 碼調(diào)用init()方法來初始化Cipher對象(初始化)。
* 它要求傳入操作模式和提供密鑰的對象,這里使用Cipher.ENCRYPT_MODE代表加密模式,以及之前創(chuàng)建的secKey對象作為密鑰。
* */
cipher.init(Cipher.ENCRYPT_MODE,secKey);
/*
* 用Cipher對象對data進(jìn)行加密操作,得到加密后的結(jié)果存儲在result字節(jié)數(shù)組中。
* */
byte[] result = cipher.doFinal(data);
return result;
}catch (Exception e){
throw new RuntimeException(" encrypt fail! ",e);
}
}
/**
* Description: 解密
*
* @param data 解密數(shù)據(jù)
* @param aesKey 解密密鑰
* @return byte[]
*/
public static byte[] decrypt(byte[] data,byte[] aesKey)
{
if (aesKey.length != 16)
{
throw new RuntimeException(" Invalid AES Key length ( must be 16 bytes)");
}
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, "AES");
byte[] encodedFormat = secretKeySpec.getEncoded();
SecretKeySpec secKey = new SecretKeySpec(encodedFormat, "AES");
/* 創(chuàng)建密碼器 */
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
/* 初始化密碼器 */
cipher.init(Cipher.DECRYPT_MODE,secKey);
byte[] result = cipher.doFinal(data);
return result;
}catch (Exception e){
throw new RuntimeException(" Decrypt Fail !",e);
}
}
/**
* Description:加密數(shù)據(jù),并轉(zhuǎn)換為Base64編碼格式!
*
* @param data 待加密數(shù)據(jù)
* @param aeskey 加密密鑰
* @return java.lang.String
*/
public static String encryptToBase64(String data,String aeskey)
{
try {
byte[] valueByte = encrypt(data.getBytes(CHAR_ENCODING), aeskey.getBytes(CHAR_ENCODING));
/* 加密數(shù)據(jù)轉(zhuǎn) Byte[]--> 換為Base64 --> String */
return Base64.encode(valueByte);
}catch (UnsupportedEncodingException e){
throw new RuntimeException(" Encrypt Fail !",e);
}
}
/**
* Description: 解密數(shù)據(jù),將Basse64格式的加密數(shù)據(jù)進(jìn)行解密操作
*
* @param data
* @param aeskey
* @return java.lang.String
*/
public static String decryptFromBase64(String data,String aeskey)
{
try {
byte[] originalData = Base64.decode(data.getBytes());
byte[] valueByte = decrypt(originalData,aeskey.getBytes(CHAR_ENCODING));
return new String(valueByte,CHAR_ENCODING);
}catch (UnsupportedEncodingException e){
throw new RuntimeException("Decrypt Fail !",e);
}
}
/**
* Description:加密數(shù)據(jù),aesKey為Base64格式時(shí),并將加密后的數(shù)據(jù)轉(zhuǎn)換為Base64編碼格式
*
* @param data
* @param aesKey
* @return java.lang.String
*/
public static String encryptWithKeyBase64(String data,String aesKey)
{
try{
byte[] valueByte = encrypt(data.getBytes(CHAR_ENCODING), Base64.decode(aesKey.getBytes()));
return Base64.encode(valueByte);
}catch (UnsupportedEncodingException e){
throw new RuntimeException("Encrypt Fail!",e);
}
}
/**
* Description: 解密數(shù)據(jù),數(shù)據(jù)源為Base64格式,且 aesKey為Base64編碼格式
*
* @param data
* @param aesKey
* @return java.lang.String
*/
public static String decryptWithKeyBase64(String data,String aesKey)
{
try {
byte[] originalDate = Base64.decode(data.getBytes());
byte[] valueByte = decrypt(originalDate,Base64.decode(aesKey.getBytes()));
return new String(valueByte,CHAR_ENCODING);
}catch (UnsupportedEncodingException e){
throw new RuntimeException("Decrypt Fail !",e);
}
}
/**
* Description:通過密鑰生成器生成一個(gè)隨機(jī)的 AES 密鑰,并將其以字節(jié)數(shù)組的形式返回。
* 主要功能是生成并返回一組隨機(jī)的密鑰字節(jié)數(shù)組,這些字節(jié)數(shù)組可用于加密和解密數(shù)據(jù)。
*
* @param
* @return byte[]
*/
public static byte[] generateRandomAesKey()
{
KeyGenerator keyGenerator = null;
try{
/*
* KeyGenerator是Java Cryptography Architecture(JCA)提供的主要密鑰生成器類之一,用于生成對稱加密算法的密鑰。
* 獲取一個(gè)用于生成AES算法密鑰的KeyGenerator實(shí)例,以便在加密和解密操作中使用該密鑰。
* */
keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM);
}catch (NoSuchAlgorithmException e){
throw new RuntimeException("GenerateRandomKey Fail !",e);
}
/*
* SecureRandom 類提供了一種用于生成加密強(qiáng)隨機(jī)數(shù)的實(shí)現(xiàn)。
* */
SecureRandom secureRandom = new SecureRandom();
/*
* 初始化密鑰生成器 keyGenerator。
* 初始化密鑰生成器時(shí)使用了 SecureRandom 實(shí)例,以確保生成的密鑰具有足夠的隨機(jī)性。
* */
keyGenerator.init(secureRandom);
/*
* 調(diào)用 generateKey() 方法,使用初始化后的 keyGenerator 生成密鑰對象 key。
* */
Key key = keyGenerator.generateKey();
//返回生成的密鑰的字節(jié)數(shù)組表示。
return key.getEncoded();
}
/**
* Description: 通過密鑰生成器生成一個(gè)隨機(jī)的 AES 密鑰,并轉(zhuǎn)化為Base64格式
*
* @param
* @return java.lang.String
*/
public static String generateRandomAesKeyWithBase64()
{
return Base64.encode(generateRandomAesKey());
}
/* ??!當(dāng)GET請求進(jìn)行加密時(shí),地址上的加密參數(shù)就以16進(jìn)制字符串的方式進(jìn)行傳輸,否則特殊符號路徑無法解析[ +、/、=]等Base64編碼格式 */
/**
* Description: 從Byte[] 數(shù)組轉(zhuǎn) 16進(jìn)制字符串
*
* @param b
* @return java.lang.String
*/
public static String toHexString(byte[] b)
{
/*
* 每個(gè)字節(jié)都可以用兩個(gè)十六進(jìn)制字符來表示,因此初始化的容量是字節(jié)數(shù)組長度的兩倍。
* */
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i<b.length ;i++)
{
/*
* 首先取字節(jié)的高四位,然后查找對應(yīng)的十六進(jìn)制字符,并將其追加到StringBuilder中
* */
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
/*
* 取字節(jié)的低四位,找到對應(yīng)的十六進(jìn)制字符,并追加到StringBuilder中。
* */
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
/**
* Description: 從16進(jìn)制字符串轉(zhuǎn) byte[] 數(shù)組
*
* @param s
* @return byte[]
*/
public static final byte[] toBytes(String s)
{
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length ; i++)
{
bytes[i] = (byte) Integer.parseInt(s.substring(2*i,2*i+2),16);
}
return bytes;
}
}
AES加解密工具類方法代碼解析(為了方便自己理解和使用,有必要簡單分類記錄一下工具類中的方法接口):
AESUtil工具類中的方法封裝的比較雜亂,通過梳理之后更加能理清每個(gè)方法的具體用法和功能!
生成AES密鑰的方法:
該工具類中總共封裝了兩種 生成 AES密鑰的方法 String getAESKey(int length) 和 String generateRandomAesKeyWithBase64()
- getAESKey 方法生成的密鑰是 由數(shù)字(0-9)、小寫字母、大寫字母隨機(jī)組成的普通字符串;
- generateRandomAesKeyWithBase64() 方法生成的密鑰是 通過javax.crypto.KeyGenerator 密鑰生成器生成Byte[] 類型的數(shù)據(jù) 在將該 byte[] 轉(zhuǎn)換為 Base64編碼格式。
圖片
AES加密數(shù)據(jù)方法:
1.AES工具類封裝的加密數(shù)據(jù)方法有以下幾種byte[] encrypt(byte[] data,byte[] aesKey)、 String encryptToBase64(String data,String aeskey) 和 String encryptWithKeyBase64(String data,String aesKey) 共三種加密方式:
注:其實(shí)其余加密方法都是基于該方法進(jìn)行封裝的。也可以根據(jù)自己需求來調(diào)整,注意區(qū)別在于傳入的數(shù)據(jù)格式有所區(qū)別??!
2.String encryptToBase64(String data,String aeskey) 該AES加密方法是通過傳入加密數(shù)據(jù)的字符串,同時(shí)傳入字符格式的AES密鑰Key(通過getAESKey生成的密鑰);方法內(nèi)部會將傳入進(jìn)來的 待加密數(shù)據(jù) data 和 aesKey密鑰轉(zhuǎn)換為 byte[] 格式,然后在調(diào)用第一種加密方法;最后生成的加密數(shù)據(jù)byte[] 也會在內(nèi)部自動轉(zhuǎn)換為Base64編碼格式 然后返回。
3.String encryptWithKeyBase64(String data,String aesKey) 該AES加密方法,需要傳入 字符串形式的加密數(shù)據(jù),以及Base64編碼格式的AES密鑰 (該密鑰主要是通過generateRandomAesKeyWithBase64() 方法生成的密鑰數(shù)據(jù) 為Base64編碼格式)。加密方法內(nèi)部在接收到 待加密數(shù)據(jù)后會自動轉(zhuǎn)換為byte[]格式;在接收到Base64編碼格式的AES密鑰后,通過Base64.decode() 將其解碼為 byte[]。然后在調(diào)用原始的加密方法對待加密數(shù)據(jù)進(jìn)行加密操作。最終加密后的數(shù)據(jù)byte[] 通過 new String(valueByte,“UTF-8”) 的方式轉(zhuǎn)換為字符串返回。
圖片
AES解密數(shù)據(jù)方法:
AES工具類中封裝的解密方法,對應(yīng)于加密方法:byte[] decrypt(byte[] data,byte[] aesKey)、 String decryptFromBase64(String data,String aeskey) 和 String decryptFromBase64(String data,String aeskey) 三種方式。
該三種方式分別與上面三種加密方式是對應(yīng)的。需要注意傳入的數(shù)據(jù)封裝格式就行。
- 第一種解密方法就需要傳入 加密后數(shù)據(jù)格式 byte[],密鑰格式 byte[]
- 第二種解密方法對應(yīng)于上面的第二種加密方法。需要傳入的加密數(shù)據(jù)為Base64編碼格式( 通過加密方法生成byte[] 后 在轉(zhuǎn)換為 Base64格式 ),需要傳入AES密鑰格式就為普通字符串格式(通過 String getAESKey(int length) 方法生成的密鑰)。
- 第三種解密方法,需要傳入的待解密數(shù)據(jù) 為Base64編碼格式,需要傳入的AES密鑰也為Base64編碼格式
圖片
String toHexString(byte[] b) 方法
該方法是將byte[] 字節(jié)數(shù)據(jù)轉(zhuǎn)換為16進(jìn)制的字符串?dāng)?shù)據(jù),后續(xù)會利用到。 比如在Get請求種傳輸加密數(shù)據(jù),如果前端加密后的數(shù)據(jù)需要放入地址中進(jìn)行傳輸?shù)胶蠖?;若采用Base64編碼格式數(shù)加密數(shù)據(jù)進(jìn)行傳輸時(shí),加密內(nèi)容會包含 +、\、= 三個(gè)符號,無法在地址中進(jìn)行傳輸了。
所以這里封裝了該方法,通過調(diào)用該方法,將加密后的byte[] 字節(jié)數(shù)據(jù)數(shù)據(jù)轉(zhuǎn)換為 HexString 16進(jìn)制字符串格式(只包含了 0~9、a、b、c、d、e、f)。這樣Get請求中的加密數(shù)據(jù)就可以通過地址進(jìn)行傳輸了
byte[] toBytes(String s) 方法
該方法于 toHexString 方法相對應(yīng),將轉(zhuǎn)換為HexString十六進(jìn)制的字符串 還原為字節(jié)數(shù)據(jù)Byte[]。
1.3 RSA加密工具類創(chuàng)建
RSA加密工具類,同樣引用了 hutool-all 依賴工具類。
package com.example.api_security_demo.utils;
import cn.hutool.core.codec.Base64Encoder;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
/**
* @ClassName : RSAUtil
* @Description : RSA加密工具類
* @Author : AD
*/
public class RSAUtil {
/**
* "SHA256withRSA" 是一種使用 SHA-256 哈希算法和 RSA 加密算法結(jié)合的數(shù)字簽名算法。
* 在這種算法中,數(shù)據(jù)首先會通過 SHA-256 進(jìn)行哈希處理,得到一個(gè)固定長度的摘要,然后使用 RSA 私鑰對這個(gè)摘要進(jìn)行加密,從而生成數(shù)字簽名。
* */
public static final String ALGORITHM_SHA256WITHRSA = "SHA256withRSA";
public static final String KEY_ALGORITHM ="RSA";
//RSA最大加密明文大小
public static final int MAX_ENCRYPT_BLOCK = 117;
//RSA最大解密密文大小
public static final int MAX_DECRYPT_BLOCK = 128;
private static char[] HEXCHAR = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* Description: 公鑰分段加密
*
* @param data 待加密源數(shù)據(jù)
* @param publicKey 公鑰(BASE64編碼)
* @param length 段長 1024長度的公鑰最大取117
* @return byte[]
*/
public static byte[] encryptByPublicKey(byte[] data,String publicKey,int length) throws Exception
{
/*
* 將BASE64編碼格式 publicKey進(jìn)行解碼
* */
byte[] publicKeyByte = decryptBASE64(publicKey);
/*
* 使用X509EncodedKeySpec類創(chuàng)建了一個(gè)X.509編碼的KeySpec對象,并將publicKeyByte作為參數(shù)傳入。
* 將公鑰 [字符串] 解碼成 [公鑰對象] ,以便用于加密數(shù)據(jù)。
* */
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyByte);
/*
* 通過KeyFactory獲取了RSA的實(shí)例
* */
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
/*
* 調(diào)用generatePublic方法使用之前創(chuàng)建的X509EncodedKeySpec對象來生成公鑰。
* */
Key generatePublicKey = keyFactory.generatePublic(x509EncodedKeySpec);
/*
* 創(chuàng)建一個(gè)Cipher實(shí)例,它是用于加密或解密數(shù)據(jù)的對象。Cipher類提供了加密和解密功能,并支持許多不同的加密算法。
* 在這里,getInstance 方法中傳入了keyFactory.getAlgorithm()[獲取與指定密鑰工廠相關(guān)聯(lián)的算法名稱。],它用于獲取與指定算法關(guān)聯(lián)的 Cipher 實(shí)例。
* */
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
/*
* 初始化 Cipher 對象。
* 在初始化過程中,指定加密模式為 ENCRYPT_MODE,并傳入了之前生成的公鑰 generatePublicKey。
* */
cipher.init(Cipher.ENCRYPT_MODE,generatePublicKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
//段落起始位置
int offSet = 0;
byte[] cache;
int i = 0;
//對數(shù)據(jù)進(jìn)行分段加密
while (inputLen - offSet > 0)
{
if (inputLen - offSet > length) {
cache = cipher.doFinal(data,offSet,length);
} else {
cache = cipher.doFinal(data,offSet,inputLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet = i * length;
}
byte[] encryptDate = out.toByteArray();
out.close();
return encryptDate;
}
/**
* Description:
*
* @param data 待解密數(shù)據(jù)
* @param privateKey 私密(BUSE64編碼)
* @param length 分段解密長度 128
* @return byte[]
*/
public static byte[] decryptByPrivateKey(byte[] data,String privateKey,int length) throws Exception
{
byte[] privateKeyByte = decryptBASE64(privateKey);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key generatePrivateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,generatePrivateKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
//對數(shù)據(jù)進(jìn)行分段解密
while (inputLen - offSet > 0)
{
if (inputLen - offSet > length)
{
cache = cipher.doFinal(data,offSet,length);
} else {
cache = cipher.doFinal(data,offSet,inputLen - offSet);
}
out.write(cache,0,cache.length);
i++;
offSet = i * length;
}
byte[] decryptData = out.toByteArray();
out.close();
return decryptData;
}
/**
* Description: BASE64解碼
*
* @param src
* @return byte[]
*/
public static byte[] decryptBASE64(String src)
{
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
try{
return decoder.decodeBuffer(src);
}catch (Exception ex){
return null;
}
}
/**
* Description: BASE64編碼
*
* @param src
* @return java.lang.String
*/
public static String encryptBASE64(byte[] src)
{
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(src);
}
/**
* Description: 從Byte[] 數(shù)組轉(zhuǎn) 16進(jìn)制字符串
*
* @param b
* @return java.lang.String
*/
public static String toHexString(byte[] b)
{
/*
* 每個(gè)字節(jié)都可以用兩個(gè)十六進(jìn)制字符來表示,因此初始化的容量是字節(jié)數(shù)組長度的兩倍。
* */
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i<b.length ;i++)
{
/*
* 首先取字節(jié)的高四位,然后查找對應(yīng)的十六進(jìn)制字符,并將其追加到StringBuilder中
* */
sb.append(HEXCHAR[(b[i] & 0xf0) >>> 4]);
/*
* 取字節(jié)的低四位,找到對應(yīng)的十六進(jìn)制字符,并追加到StringBuilder中。
* */
sb.append(HEXCHAR[b[i] & 0x0f]);
}
return sb.toString();
}
/**
* Description: 從16進(jìn)制字符串轉(zhuǎn) byte[] 數(shù)組
*
* @param s
* @return byte[]
*/
public static final byte[] toBytes(String s)
{
byte[] bytes;
bytes = new byte[s.length() / 2];
for (int i = 0; i < bytes.length ; i++)
{
bytes[i] = (byte) Integer.parseInt(s.substring(2*i,2*i+2),16);
}
return bytes;
}
/**
* Description: 判斷對象是否為null
*/
public static boolean isEmpty(Object str) {
return (str == null || "".equals(str));
}
/**
* RSA 公鑰私鑰生成器
* */
public static Map generateRandomToBase64Key() throws Exception{
String KEY_ALGORITHM ="RSA";
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
//密鑰位數(shù)
keyPairGenerator.initialize(1024);
//創(chuàng)建公鑰/私鑰
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
byte[] publicKeyEncoded = publicKey.getEncoded();
byte[] privateKeyEncoded = privateKey.getEncoded();
HashMap<String,String> map = new HashMap<>();
map.put("publicKey", Base64Encoder.encode(publicKeyEncoded));
map.put("privateKey",Base64Encoder.encode(privateKeyEncoded));
return map;
}
/**
* Description: 根據(jù)請求參數(shù)Map集合,排號順序Sort,組裝生成對應(yīng)請求中的簽名參數(shù)sign
*
* @param map 請求參數(shù)Map集合
* @param allowValueNull 是否允許map中的值為null; true允許:若允許為空則會出現(xiàn)a=&b=
* @return java.lang.String
*/
public static String generateSortSign(Map<String,String> map,boolean allowValueNull)
{
List<String> keys = new ArrayList<>(map.size());
for ( String key : map.keySet() )
{
/*
* 排除下列參數(shù)數(shù)據(jù)
* 1.不允許出現(xiàn)空value 且 map中為null 的鍵值對
* 2.參數(shù)簽名內(nèi)容鍵值對
* */
if ( (!allowValueNull && isEmpty(map.get(key))) || "sign".equals(key) || "signValue".equals(key) )
{
continue;
}
keys.add(key);
}
/*
* sort靜態(tài)方法用于按自然順序或自定義順序?qū)ist進(jìn)行排序
* */
Collections.sort(keys);
StringBuffer stringBuffer = new StringBuffer();
boolean isFirst = true;
for (String key : keys){
if (isFirst){
stringBuffer.append(key).append("=").append(map.get(key));
isFirst = false;
continue;
}
stringBuffer.append("&").append(key).append("=").append(map.get(key));
}
return stringBuffer.toString();
}
/**
* Description: 用于生成數(shù)據(jù)的數(shù)字簽名,并將簽名數(shù)據(jù)轉(zhuǎn)換為十六進(jìn)制字符串格式返回
*
* @param rawDate 簽名裸數(shù)據(jù)
* @param privateKey 私鑰
* @param algorithm 簽名驗(yàn)算算法
* @return java.lang.String
*/
public static String generateSign(byte[] rawDate,String privateKey,String algorithm) throws Exception
{
byte[] privateKeyBytes = decryptBASE64(privateKey);
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey generatePrivate = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
/*
* 使用指定的簽名算法algorithm,通過Signature實(shí)例獲取簽名對象signature。
* */
Signature signature = Signature.getInstance(algorithm);
/*
* 初始化簽名對象,傳入生成的私鑰generatePrivate。
* */
signature.initSign(generatePrivate);
/*
* 將要簽名的裸數(shù)據(jù)rawData傳入簽名對象。
* */
signature.update(rawDate);
/*
* 生成簽名數(shù)據(jù)sign
* */
byte[] sign = signature.sign();
return toHexString(sign);
}
/**
* Description: 驗(yàn)證簽名
*
* @param data 請求數(shù)據(jù)
* @param publicKey 公鑰
* @param sign 簽名數(shù)據(jù)
* @param algorithm 簽名驗(yàn)算算法
* @return boolean
*/
public static boolean verify(byte[] data,String publicKey,String sign,String algorithm) throws Exception
{
byte[] publicKeyBytes = decryptBASE64(publicKey);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey generatePublicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance(algorithm);
signature.initVerify(generatePublicKey);
signature.update(data);
return signature.verify( toBytes(sign) );
}
}
RSAUtil加解密工具類方法代碼解析(為了方便自己理解和使用,有必要簡單分類記錄一下工具類中的方法接口):
- 生成密鑰對方法:
Map generateRandomToBase64Key()
- byte[] 與 Base64編碼互相轉(zhuǎn)換的方法:
byte[] decryptBASE64(String src)
String encryptBASE64(byte[] src)
- HexString 十六進(jìn)制字符串 與 byte[] 字節(jié)數(shù)組 互相轉(zhuǎn)換的方法:
String toHexString(byte[] b)
byte[] toBytes(String s)
- RSA加密/解密方法:
byte[] encryptByPublicKey(byte[] data,String publicKey,int length)
RSAUtil工具類中的加密接口就只有一個(gè),最終加密后的數(shù)據(jù)會以字節(jié)數(shù)組 byte[] 格式返回。最終用戶想將密文以什么形式傳輸都可以( String() 字符串形式、Base64編碼格式、HexString十六進(jìn)制字符串形式 )。
byte[] decryptByPrivateKey(byte[] data,String privateKey,int length)
在解碼數(shù)據(jù)時(shí),必須將密文數(shù)據(jù)根據(jù)對應(yīng)的數(shù)據(jù)格式轉(zhuǎn)換為 byte[] 后傳入解碼方法。
- Base64格式編碼解碼方法:
byte[] decryptBASE64(String src)
String encryptBASE64(byte[] src)
二、解密傳輸數(shù)據(jù)實(shí)現(xiàn)方案
依托與SpringBoot進(jìn)行開發(fā),在后臺中需要解密的請求接口,是采用了FIlter來實(shí)現(xiàn)解密操作。
圖片
采用 FIlter 來對加密數(shù)據(jù)進(jìn)行解密的好處之一是:Filter 獲取到參數(shù)后,可以將密文參數(shù)解密之后,重新重寫請求參數(shù)。這樣在Controller層處理業(yè)務(wù)邏的接口可以按照正常方式進(jìn)行開發(fā),@RequestBody、@RequestParam 等注解都能正常使用。
2.1 Request 流只能讀取一次的問題
在接口調(diào)用連接中,request的請求流只能調(diào)用一次,處理之后,如果之后還需要用到請求流獲取數(shù)據(jù),就會發(fā)現(xiàn)數(shù)據(jù)為空。比如使用了filter或者aop在接口處理之前,獲取了request中的數(shù)據(jù),對參數(shù)進(jìn)行了校驗(yàn),那么之后就不能在獲取request請求流了。
解決辦法:
繼承HttpServletRequestWrapper,將請求中的流copy一份,復(fù)寫getInputStream和getReader等方法供外部使用。每次調(diào)用后的getInputStream方法都是從復(fù)制出來的二進(jìn)制數(shù)組中進(jìn)行獲取,這個(gè)二進(jìn)制數(shù)組在對象存在期間一致存在。通過HttpServletRequestWrapper可以獲取到前端加密的請求參數(shù),同時(shí)也可以將解密后的參數(shù)設(shè)置進(jìn)去。
- Post請求: 采用Filter來實(shí)現(xiàn) 加密傳輸數(shù)據(jù)的解密功能,在解密對應(yīng)request請求流中的數(shù)據(jù)之后。將解密后的數(shù)據(jù)替換至自定義封裝的requestWrapper對象中 body中。
- Get請求: 地址欄中添加了加密數(shù)據(jù),在Filter進(jìn)行解密之后,會將請求數(shù)據(jù)存入自定義封裝的 requestWrapper 對象中的 Map集合數(shù)據(jù)中。在重寫父類的 getParament() 等方法。
這里需要特別注意;對于MultipartRequest請求如果不做處理HttpServletRequestWrapper中是獲取不到參數(shù)的;
自定義 RequestWrapper對象:
package com.example.api_security_demo.common.core.wrapper;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartRequest;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/**
* @ClassName : RequestWrapper
* @Description : 自定義Request,解決request請求流中的數(shù)據(jù)二次或多次使用問題
* 繼承HttpServletRequestWrapper,將請求體中的流copy一份,覆寫getInputStream()和getReader()方法供外部使用。
* 每次調(diào)用覆寫后的getInputStream()方法都是從復(fù)制出來的二進(jìn)制數(shù)組中進(jìn)行獲取,這個(gè)二進(jìn)制數(shù)組在對象存在期間一直存在,這樣就實(shí)現(xiàn)了流的重復(fù)讀取。
* @Author : AD
*/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 存儲Body數(shù)據(jù)
* */
private byte[] body;
//============
/**
* 保存原始Request對象,當(dāng)請求為 MultipartRequest 文件上傳類的請求操作
*/
private HttpServletRequest request;
/**
* 額外參數(shù)可以加到這個(gè)里面 重寫getParameter() 方法 ,從而使請求中不存在的參數(shù),通過該Map集合中獲取??!
*/
private Map<String, String[]> parameterMap = new LinkedHashMap<>();
/**
* Description: requestWrapper 請求包裝類的構(gòu)造方法
*
* @param request
* @return
*/
public RequestWrapper(HttpServletRequest request)throws IOException
{
super(request);
//[文件上傳相關(guān)的操作]
this.request = request;
if(request instanceof MultipartRequest){
// 如果是[文件上傳類]請求
this.parseBody(request);
}else{
//[普通請求類]將Body數(shù)據(jù)存儲起來
String bodyString = getBodyString(request);
body = bodyString.getBytes(Charset.defaultCharset());
}
}
/* [MultipartRequest 文件上傳]相關(guān)操作接口 */
/**
* 如果是 MultipartRequest,需要解析參數(shù)信息
*/
private void parseBody(HttpServletRequest request) {
Map<String,Object> parameterMap = new LinkedHashMap<>();
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()){
String name = parameterNames.nextElement();
String[] values = request.getParameterValues(name);
parameterMap.put(name, (values !=null && values.length == 1) ? values[0] : values);
}
// 將解析出來的參數(shù),轉(zhuǎn)換成JSON并設(shè)置到body中保存
this.body = JSONObject.toJSONString(parameterMap).getBytes(Charset.defaultCharset());
}
public void setBody(byte[] body)
{
this.body = body;
try {
if(this.request instanceof MultipartRequest){
//[文件上傳請求相關(guān)的操作]
//todo 將Json格式body數(shù)據(jù)轉(zhuǎn)換為mp
//this.setParameterMap(JsonUtil.json2map(body));
String bodyStr = new String(body, "UTF-8");
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
Map<String, Object> bodyMap = objectMapper.readValue(bodyStr, Map.class);
this.setParameterMap(bodyMap);
}
} catch (Exception e) {
log.error("轉(zhuǎn)換參數(shù)異常,參數(shù):{},異常:{}",body, e);
}
}
/**
* Description:讀取請全體Body中數(shù)據(jù) [從 requestWrapper中讀取]
*
* @param
* @return java.lang.String
*/
public String getBodyString(){
final InputStream inputStream = new ByteArrayInputStream(body);
return inputStreamToString(inputStream);
}
/**
* Description: 讀取請求體Body中數(shù)據(jù) [從HttpServletRequest中讀取]
*
* @param request
* @return java.lang.String
*/
public String getBodyString(final ServletRequest request)
{
try {
return inputStreamToString(request.getInputStream());
}catch (IOException e){
log.error("Read Request Body IO_Stream Fail !",e);
throw new RuntimeException(e);
}
}
/**
* Description: 將inputStream流里面的數(shù)據(jù)讀取出來并轉(zhuǎn)換為字符串形式
*
* @param inputStream
* @return java.lang.String
*/
private String inputStreamToString(InputStream inputStream){
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null){
sb.append(line);
}
}catch (IOException e){
log.error("BufferedReader is Fail !",e);
throw new RuntimeException(e);
}finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return sb.toString();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return inputStream.read();
}
};
}
// [Get請求相關(guān)操作,封裝Request.getParameter()中的相關(guān)參數(shù) ]
/**
* Description: The default behavior of this method is to return getParameter(Stringname) on the wrapped request object.
*
* @param name
* @return java.lang.String
* @date 2024-05-13
*/
@Override
public String getParameter(String name) {
String result = super.getParameter(name);
// 如果參數(shù)獲取不到則嘗試從參數(shù)(自定義封裝的存貯零時(shí)請求數(shù)據(jù)的集合)Map中獲取,并且只返回第一個(gè)
if(result==null && this.parameterMap.containsKey(name)){
result = this.parameterMap.get(name)[0];
}
return result;
}
/**
* The default behavior of this method is to return getParameterMap() on the
* wrapped request object.
*/
@Override
public Map<String, String[]> getParameterMap() {
// 需要將原有的參數(shù)加上新參數(shù) 返回
Map<String,String[]> map = new HashMap<>(super.getParameterMap());
for(String key: this.parameterMap.keySet()){
map.put(key, this.parameterMap.get(key));
}
return Collections.unmodifiableMap(map);
}
/**
* The default behavior of this method is to return
* getParameterValues(String name) on the wrapped request object.
*
* @param name
*/
@Override
public String[] getParameterValues(String name) {
String[] result = super.getParameterValues(name);
if(result == null && this.parameterMap.containsKey(name)){
result = this.parameterMap.get(name);
}
return result;
}
/**
* The default behavior of this method is to return getParameterNames() on
* the wrapped request object.
*/
@Override
public Enumeration<String> getParameterNames() {
Enumeration<String> parameterNames = super.getParameterNames();
Set<String> names = new LinkedHashSet<>();
if(parameterNames !=null){
while(parameterNames.hasMoreElements()){
names.add(parameterNames.nextElement());
}
}
// 添加后期設(shè)置的參數(shù)Map
if(!this.parameterMap.isEmpty()){
names.addAll(this.parameterMap.keySet());
}
return Collections.enumeration(names);
}
/**
* 設(shè)置參數(shù)map
* @param json2map
*/
public void setParameterMap(Map<String, Object> json2map) {
if(json2map != null && !json2map.isEmpty()) {
for (String key : json2map.keySet()){
//獲取map中對應(yīng)key的value
Object value = json2map.get(key);
if(this.parameterMap.containsKey(key)){
//如果額外參數(shù)HashLink中包含該參數(shù),則在賦值加入到String[] 中
String[] originalArray = this.parameterMap.get(key);
int originalLength = originalArray.length;
originalArray = Arrays.copyOf(originalArray,originalLength + 1);
originalArray[originalLength] = String.valueOf(value);
//this.parameterMap.put(key, Collection.add(this.parameterMap.get(key), value));
this.parameterMap.put(key,originalArray);
}else{
this.parameterMap.put(key, new String[]{String.valueOf(value)});
}
}
}
}
}
RequestWrapper類方法代碼解析(為了方便自己理解和使用,有必要簡單分類記錄一下工具類中的方法接口):這里自定義封裝的 RequestWrapper對象,繼承 HttpServletRequestWrapper。
- 通過重寫 getReader() 、getInputStream() 等方法,從而可以實(shí)現(xiàn)通過request對象讀取body數(shù)據(jù)時(shí),能夠直接獲取到該對象中我們自己封裝的用于存放請求體數(shù)據(jù)的屬性byte[] body。
- void setBody(byte[] body) 方法可以用來給自定義封裝的屬性body進(jìn)行賦值,在 解密請求數(shù)據(jù)的 FIlter中,解密了body數(shù)據(jù)后,通過調(diào)用該方法將解密后的body數(shù)據(jù)存入requestWrapper對象。這樣在后續(xù)的業(yè)務(wù)操作中直接通過request對象獲取到的body數(shù)據(jù)就是已經(jīng)解密的數(shù)據(jù)。實(shí)現(xiàn)了業(yè)務(wù)無感知!
- void setParameterMap(Map<String, Object> json2map) 在解密Filter中,將Get請求中地址上的加密數(shù)據(jù)進(jìn)行解密之后,調(diào)用該方法就將解密后的Get請求數(shù)據(jù)封裝到 requestWrapper對象中的Map集合中實(shí)現(xiàn)后續(xù)調(diào)用request.getParameter() 方法時(shí)能夠獲取到解密后的參數(shù)。
- 重寫父類 getParameter(String name)、Map<String, String[]> getParameterMap()、 String[] getParameterValues(String name)等方法,實(shí)習(xí)在getRequestParameter()數(shù)據(jù)時(shí),也能夠在requestWrapper對象中的Map集合中獲取參數(shù)數(shù)據(jù)。
2.2 過濾器Filter解密請求參數(shù)
這里封裝的解密參數(shù)過濾器Filter中,首先需要通過請求頭中的 aksEncrypt數(shù)據(jù)判斷該請求是否為加密請求,如果不是則直接放行不做解密操作。如果需要解密的請求,首先判斷請求類型在進(jìn)行對應(yīng)的解密處理。
圖片
Filter解密數(shù)據(jù)過濾器代碼:
package com.example.api_security_demo.filter;
import com.alibaba.fastjson2.JSONObject;
import com.example.api_security_demo.common.core.wrapper.RequestWrapper;
import com.example.api_security_demo.utils.AESUtil;
import com.example.api_security_demo.utils.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName : DecryptReplaceStreamFilter
* @Description :Filter過濾器 解密請求參數(shù)。同時(shí)替換請求體,使后續(xù)操作無感知加密??!
* @Author : AD
*/
@Slf4j
public class DecryptReplaceStreamFilter implements Filter {
/*
* AKS(Authentication Key Management System),采用無明文密鑰的方式對數(shù)據(jù)進(jìn)行加密保護(hù),加解密運(yùn)算由統(tǒng)一的安全計(jì)算中心完成,AKS系統(tǒng)以接口的方式為對各個(gè)業(yè)務(wù)線提供加密解服務(wù)。
* 各個(gè)系統(tǒng)不再使用明文密鑰,只使用密鑰別名,調(diào)用簡單的加解密函數(shù),完成對數(shù)據(jù)的保護(hù)。
* */
//請求頭標(biāo)簽開關(guān):是否需要加密解密
private static final String AKS_ENABLE = "aksEncrypt";
//GET請求加密數(shù)據(jù)Key
public static final String AKS_PARAMETER = "encryptData";
private static final String METHOD_GET = "GET";
private static final String METHOD_POST ="POST";
//POST請求加密數(shù)據(jù)Key
private static final String AKS_BODY ="content";
//AES密鑰Key
private static final String AES_KEY = "aesKey";
/**
* Feign是聲明式Web Service客戶端,它讓微服務(wù)之間的調(diào)用變得更簡單,類似controller調(diào)用service。
* Feign內(nèi)部調(diào)用時(shí),請求頭中標(biāo)注請求源
* */
public static final String SOURCE_KEY = "api-source";
public static final String SOURCE_VALUE = "inner-api";
@Value("${Rsa.PrivateKey}")
private String privateKey;
@Value("${API.Security.enable}")
private boolean securityEnable;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//轉(zhuǎn)換為自己Wrapper,實(shí)現(xiàn)多次讀寫
RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
String contentType = requestWrapper.getContentType(); //請求頭中獲取Content-Type數(shù)據(jù)
String requestURI = requestWrapper.getRequestURI();
//配置文件配置是否開啟加解密功能
if (!securityEnable)
{
log.info("未開啟接口安全加密傳輸! 無需解密請求參數(shù)!");
filterChain.doFilter(requestWrapper,servletResponse);
return;
}
//通過請求頭參數(shù)判斷該請求是否需要解密處理
if (!needAks(requestWrapper)){
log.info("請求:{},非加密請求,無需解密操作!",requestURI);
filterChain.doFilter(requestWrapper,servletResponse);
return;
}
/*
* [該功能暫時(shí)不用管,因?yàn)樵谡埱箢^中不添加 aksEncrypt:true 鍵值對,請求接口時(shí)同樣不會去進(jìn)行解密請求數(shù)據(jù)的操作]
* */
//Feign服務(wù)端調(diào)用內(nèi)部請求,按照不加密的邏輯放行[Feign是聲明式Web Service客戶端,它讓微服務(wù)之間的調(diào)用變得更簡單,類似controller調(diào)用service。]
//前端 --> A --> b --> c
String sourceKey = requestWrapper.getHeader(SOURCE_KEY);
if (!ObjectUtils.isEmpty(sourceKey) && sourceKey.equals(SOURCE_VALUE) ){
log.info("內(nèi)部請求,無效加密解密接口數(shù)據(jù)!");
filterChain.doFilter(requestWrapper,servletResponse);
return;
}
/*
* POST請求進(jìn)行解密工作
* */
if (requestWrapper.getMethod().equalsIgnoreCase(METHOD_POST)){
//讀取JSON請求體數(shù)據(jù)
StringBuffer bodyInfo = new StringBuffer();
String line = null;
BufferedReader reader = null;
reader = requestWrapper.getReader();
while ( ( line = reader.readLine() ) != null ){
bodyInfo.append(line);
}
//解密請求體數(shù)據(jù)
JSONObject jsonObject = JSONObject.parseObject(bodyInfo.toString());
log.info("Post請求:{},待解密請求參數(shù):{}", requestURI, JSONObject.toJSONString(jsonObject));
//獲取通過AES加密之后的密文
String content = jsonObject.getString(AKS_BODY);
//獲取通過RSA加密之后的AES密鑰KEy
String aesKey = jsonObject.getString(AES_KEY);
//RSAUtil解密出AES密鑰Key
try {
aesKey = new String(RSAUtil.decryptByPrivateKey(RSAUtil.toBytes(aesKey),privateKey,RSAUtil.MAX_DECRYPT_BLOCK),"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
/*
* 方式1.將解密之后的數(shù)據(jù)+aesKey [放入body中,棄:會影響body結(jié)構(gòu)] ( 滿足在AOP操作中對出參數(shù)據(jù)進(jìn)行加密 ) 一并交給下游業(yè)務(wù)。
*/
//JSONObject requestBody = JSONObject.parseObject(data);
//requestBody.put(AES_KEY,aesKey);
/*
* 方式2.將其放入[請求對象屬性中中],不影響請求體結(jié)構(gòu)!
*/
//requestWrapper.setAttribute(AES_KEY,aesKey);
/*
* 方式3.將其放入[放入RequestWrapper封裝的額外參數(shù)Map中],不影響請求體結(jié)構(gòu)!
* */
HashMap<String, Object> map = new HashMap<>();
map.put(AES_KEY,aesKey);
requestWrapper.setParameterMap(map);
//AESUtil + aesKey 解密json數(shù)據(jù)
String decryptData = AESUtil.decryptFromBase64(content, aesKey);
log.info("Get請求:{},解密之后參數(shù):{}", requestURI, decryptData);
//重置Json請求體,保證下游業(yè)務(wù)無感知獲取數(shù)據(jù)
//requestWrapper.setBody(requestBody.toJSONString().getBytes());
requestWrapper.setBody(decryptData.getBytes());
}
/*
* GET請求解密處理:[AES密鑰Key放置在請求頭中]
* */
else if (requestWrapper.getMethod().equalsIgnoreCase(METHOD_GET))
{
//Get請求中 獲取到指定加密的參數(shù) 然后進(jìn)行解密操作
String encryptData = requestWrapper.getParameter(AKS_PARAMETER);
log.info("Get請求:{},待解密請求參數(shù):{}", requestWrapper.getRequestURI(), encryptData);
// 先解密 存放在請求頭中且經(jīng)過RSA加密過的AES密鑰
String aesKey = requestWrapper.getHeader(AES_KEY);
if (encryptData != null && !encryptData.isEmpty() && aesKey != null && !aesKey.isEmpty()){
try {
byte[] aesKeyByte = RSAUtil.decryptByPrivateKey(RSAUtil.toBytes(aesKey), privateKey, RSAUtil.MAX_DECRYPT_BLOCK);
aesKey = new String(aesKeyByte,"UTF-8");
System.out.println("aesKey.toString() = " + aesKey.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
//Get請求中的加密數(shù)據(jù)是以16進(jìn)制字符串方式傳輸
byte[] encryptDataByte = AESUtil.toBytes(encryptData);
System.out.println("Arrays.toString(encryptDataByte) = " + Arrays.toString(encryptDataByte));
// 解密數(shù)據(jù)操作 AKS_PARAMETER
String decryptData = new String(AESUtil.decrypt(encryptDataByte,aesKey.getBytes("UTF-8")),"UTF-8");
log.info("Get請求:{},解密之后參數(shù):{}", requestURI, decryptData);
//將GET請求中的Parameter參數(shù)賦值入RequestWrapper中封裝的其它參數(shù)存放集合Map中
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
Map<String, Object> map = objectMapper.readValue(decryptData, Map.class);
//將aseKey數(shù)據(jù)也存入map額外參數(shù)中
map.put("aesKey",aesKey);
requestWrapper.setParameterMap(map);
}
}
filterChain.doFilter(requestWrapper,servletResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void destroy() {
Filter.super.destroy();
}
/**
* Description: 判斷當(dāng)前請求是否需要加密解密數(shù)據(jù)
*
* @param request
* @return boolean
*/
private boolean needAks(HttpServletRequest request){
String enableAKS = request.getHeader(AKS_ENABLE);
return (enableAKS != null && enableAKS.equalsIgnoreCase("true"))? true: false;
}
}
代碼解析:
- 代碼中通過三重方式放到是否需要解密請求接口。一個(gè)是配置文件中讀取的開關(guān)配置、一個(gè)是通過請求頭中是否開啟加密傳輸?shù)臉?biāo)識(也就是在發(fā)送加密接口時(shí),都需要在請求頭上封裝該開關(guān))、Feign服務(wù)端調(diào)用內(nèi)部請求,按照不加密的邏輯放行。
- 解密方式按照文章開頭采用的方案,先用RSA密鑰解密出隨機(jī)的AES密鑰,在通過密鑰解密密文。
- 對應(yīng)Get請求和Post請求的解密方式兩點(diǎn)區(qū)別。Post整個(gè)請求體都是加密參數(shù)即body數(shù)據(jù)通過Base64方式傳輸進(jìn)來的;Get請求中的加密參數(shù)需要使用:encryptData,由于需要放入路徑中,Base64編碼格式中含有+、\、=等特殊符號無法進(jìn)行傳輸和解析,所以Get請求中的加密數(shù)據(jù)是采用HexString格式進(jìn)行傳輸?shù)模诮饷軙r(shí)也需要對應(yīng)的方法進(jìn)行轉(zhuǎn)換為Byte[]后在進(jìn)行解密操作。
- 關(guān)于AES密鑰的存放位置。Post請求中的AES密鑰是存入body中存入過來的,而Get請求中的AES密鑰是存放在請求頭中傳遞過來的,所以在解密對應(yīng)請求方式的密文時(shí),注意AES密鑰的獲取方式。
- 關(guān)鍵解密后的AES密鑰,需要一并交給下游業(yè)務(wù)。滿足在AOP操作中對出參數(shù)據(jù)進(jìn)行加密,所以解密出來的AES密鑰也需要存入requestWrapper對象的Map集合中,方便下游業(yè)務(wù)獲取。
Filter過濾器注冊配置類:
需要注意解密過濾器Filter 的優(yōu)先級一點(diǎn)要設(shè)置為最高優(yōu)先級registration.setOrder(1);,首先需要該過濾器對加密數(shù)據(jù)進(jìn)行解密后在重新封裝請求,才能使后續(xù)的業(yè)務(wù)數(shù)據(jù)能直接獲取到解密后的數(shù)據(jù),達(dá)到無感知的效果。
package com.example.api_security_demo.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
/**
* @ClassName : WebAllHandlerConfig
* @Description : 過濾器、監(jiān)聽器、攔截器 前置處理配置類
* @Author : AD
*/
@Configuration
public class WebAllHandlerConfig {
/**
* 注冊過濾器
* */
@Bean
public FilterRegistrationBean AllFilterRegistration(){
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
registration.setFilter(decryptReplaceStreamFilter());
registration.addUrlPatterns("/*");
registration.setName("APISecurityFilter");
registration.setOrder(1);
return registration;
}
@Bean(name = "decryptReplaceStreamFilter")
public Filter decryptReplaceStreamFilter(){
return new DecryptReplaceStreamFilter();
}
}
三、響應(yīng)數(shù)據(jù)加密實(shí)現(xiàn)方案
響應(yīng)數(shù)據(jù)加密的實(shí)現(xiàn)方式是采用AOP來實(shí)現(xiàn),可以對返回的結(jié)果對象進(jìn)行處理,而Filter只能拿到Request與Response對象,處理不方便;
這里的響應(yīng)數(shù)據(jù)加密方案就簡單采用的是AES加密,通過前端傳來的隨機(jī)AES進(jìn)行加密響應(yīng)數(shù)據(jù)后在響應(yīng)給前端!
這里響應(yīng)加密的開啟方式是通過自定義注解來實(shí)現(xiàn)的,創(chuàng)建自定義一個(gè)自定義注解,作為響應(yīng)數(shù)據(jù)加密的切點(diǎn),就實(shí)現(xiàn)了響應(yīng)數(shù)據(jù)是否加密的開啟。
圖片
3.1 自定義注解(開啟加密的注解):
package com.example.api_security_demo.common.core.annotation;
import java.lang.annotation.*;
/**
* @ClassName : ResponseEncrypt
* @Description : 響應(yīng)數(shù)據(jù)加密開啟注解
* @Author : AD
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
//@Documented
public @interface ResponseEncrypt {
}
3.2 AOP實(shí)現(xiàn)響應(yīng)數(shù)據(jù)加密功能:
需要注意,這里的響應(yīng)加密AOP的優(yōu)先級也要設(shè)置為最高@Order(value = 0),從而使最先開始的AOP能最后結(jié)束,這樣才能保證 加密響應(yīng)的AOP最終處理的響應(yīng)數(shù)據(jù)是所以業(yè)務(wù)邏輯都處理結(jié)束后最終的響應(yīng)結(jié)果,然后進(jìn)行加密處理后響應(yīng)給前端。
package com.example.api_security_demo.aop;
import com.example.api_security_demo.common.R;
import com.example.api_security_demo.common.core.annotation.ResponseEncrypt;
import com.example.api_security_demo.utils.AESUtil;
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.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @ClassName : ResponseEncryptAOP
* @Description : 傳輸加密模塊AOP,對接口的出參進(jìn)行加密,注意順序不能亂,
* 此AOP必須第一個(gè)執(zhí)行,因?yàn)樽钕葓?zhí)行的最后結(jié)束,這樣才能在各個(gè)AOP都執(zhí)行完畢之后完成最后的加密
* @Author : AD
*/
@Order(value = 0)
@Aspect
@Component
public class ResponseEncryptAop {
@Pointcut("@annotation(com.example.api_security_demo.common.core.annotation.ResponseEncrypt)")
public void point(){}
/**
* 環(huán)繞增強(qiáng),加密出參
* */
@Around(value = "point() && @annotation(responseEncrypt)")
public Object aroundEncrypt(ProceedingJoinPoint joinPoint, ResponseEncrypt responseEncrypt) throws Throwable {
//返回的結(jié)合
Object returnValue = null;
//從上下文中提取
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//業(yè)務(wù)執(zhí)行返回結(jié)果
returnValue = joinPoint.proceed();
System.out.println("returnValue.toString() = " + returnValue.toString());
//獲取到前端傳遞過來的AES密鑰,然后對響應(yīng)數(shù)據(jù)進(jìn)行AES加密操作
String aesKey = request.getParameter("aesKey");
System.out.println("aesKey = " + aesKey);
String encryptToBase64Data = AESUtil.encryptToBase64(returnValue.toString(), aesKey);
returnValue = R.ok(encryptToBase64Data);
return returnValue;
}
}
四、測試相關(guān)的類
4.1 測試類實(shí)體封裝
package com.example.api_security_demo.controller;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
/**
* @ClassName : TbStudenEntity
* @Description : 測試實(shí)體類
* @Author : AD
*/
@Data
@Accessors(chain = true)
@ToString
public class TbStudentEntity {
int id;
String name;
String sex;
int age;
}
4.2 測試接口Controller層封裝
package com.example.api_security_demo.controller;
import com.example.api_security_demo.common.R;
import com.example.api_security_demo.common.core.annotation.ResponseEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName : TbStudentController
* @Description : 前端控制器Controller測試類
* @Author : AD
*/
@RestController
@RequestMapping("/demo")
@Slf4j
public class TbStudentController {
@PostMapping("/encryptPost")
@ResponseEncrypt
public R postDemo(@RequestBody TbStudentEntity tbStudentEntity,HttpServletRequest request){
System.out.println("request.getParameter(\"aesKey\") = " + request.getParameter("aesKey"));
//System.out.println("request.getAttribute(\"aesKey\") = " + request.getAttribute("aesKey"));
System.out.println("tbStudentEntity = " + tbStudentEntity);
return R.ok(tbStudentEntity.toString());
}
@GetMapping("/encryptGet")
@ResponseEncrypt
public R postDemoGet(HttpServletRequest request,@RequestParam String id,@RequestParam String name,@RequestParam String aesKey ){
System.out.println("id = " + id);
System.out.println("name = " + name);
System.out.println("aesKey = " + aesKey);
System.out.println("request.getParameter(\"age\") = " + request.getParameter("age"));
//System.out.println("request.getAttribute(DecryptReplaceStreamFilter.AKS_PARAMETER) = " + request.getAttribute(DecryptReplaceStreamFilter.AKS_PARAMETER));
return R.ok();
}
}
4.3 前端模擬生成加密數(shù)據(jù)
package com.example.api_security_demo.utils;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName : UtilsTestClass
* @Description : 工具類測試類
* @Author : AD
*/
@Slf4j
public class UtilsTestClass {
/**
* 可以將其放入配置文件中進(jìn)行讀取
* */
String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI7HE0aW9ILCMkfoAJYmAG+5RBRhU2Itebf04GUtnYMuR6Rl1GJKec7JKuM/8xSindH4jn6Vz3oARTjbCn4CxjbtQPys5i8VeXxgzzqhE34LY0Rt62Qy8UVS113454DTwZZR9BjmPQSxMaftQHMgeDjXVwLUt0a6CmRiZKOjw8WQIDAQAB";
String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMjscTRpb0gsIyR+gAliYAb7lEFGFTYi15t/TgZS2dgy5HpGXUYkp5zskq4z/zFKKd0fiOfpXPegBFONsKfgLGNu1A/KzmLxV5fGDPOqETfgtjRG3rZDLxRVLXXfjngNPBllH0GOY9BLExp+1AcyB4ONdXAtS3RroKZGJko6PDxZAgMBAAECgYBRUHdkKcNypwI188gnhBuu18QhQpa1CRbPBI90ObWWLMqQvcdj6tO2y3t1au+9Z/FXXzrN+IC6apU1p2M2HaB4iPdW+2Vm0DaRN7XJPzBdJqVASYVJ2oWWLWCkG05mS2pAgcMlxV3TLen7iBFKTjgZhdLIal8JYgyi6XWdNlAtAQJBAPjCtpmXuAS9luyXo2ExEauKEC2uC06FeZqgM6u1rTqsqUE5kGpmJ1DiERuOcQxn8i+mlnJ1Urmw8ltMxmnJAiECQQDOxVbjUXWolwRF8lsOeZ9XGGc/45pE7J8DubEV0Ii1RVckMyTkXmgNAupE7Xq9cgNMpNBRUQEDNzSHhA8rqGM5AkBuwWrBac6RtcPLpRwl+s3uPTNE01fPZxgkYy1+Rw5QsG1PUAzfgooAthZ92Wa16lXnJ1mWrmvdp03Qnpc8pDVhAkBoqWD6vV/2D0L9eNh4cj2iY1rX7whGfRNcWmD1rtGUF94tF6pD4jl+5Ivaie6H+C8NW5uKnZsKmqX/NmxLZ/eZAkBDXRX7YgMG4PLXcjPT4ot6DEJDjuSVb1LhwucL6QFFYhZloH3/9XQS3T9XB/2F61tdh5Jd3FaCD7WeXJCzW+64";
/**
* Description: 測試獲取密鑰的方法
*/
@Test
public void testGetASK() throws Exception {
// AES密鑰
String aesKey = AESUtil.getAESKey(16);
System.out.println("aesKey = " + aesKey);
// AES Base64類型密鑰
String base64AesKey = AESUtil.generateRandomAesKeyWithBase64();
System.out.println("base64AesKey = " + base64AesKey);
//RSA 私鑰公鑰
Map map = RSAUtil.generateRandomToBase64Key();
System.out.println("map.get(\"privateKey\") = " + map.get("privateKey"));
System.out.println("map.get(\"publicKey\") = " + map.get("publicKey"));
}
/**
* Description: post請求加密傳輸,請求體body封裝測試
*
* @param
* @return void
*/
@Test
public void postRequestBodyEncryptTest() throws Exception {
//自定義方式獲取 aesKey
String aesKey = AESUtil.getAESKey(16);
//內(nèi)部方式獲取 Base64AesKey
String base64AesKey = AESUtil.generateRandomAesKeyWithBase64();
//創(chuàng)建請求體body數(shù)據(jù) content
//模擬業(yè)務(wù)數(shù)據(jù)Json,并用AES密鑰Key進(jìn)行加密
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", 15);
dataMap.put("name", "張三");
dataMap.put("sex", "男");
dataMap.put("age", 20);
JSONObject dataJson = new JSONObject(dataMap);
String contentJson = JSONObject.toJSONString(dataJson);
//AES 加密業(yè)務(wù)數(shù)據(jù)
String content = AESUtil.encryptToBase64(contentJson, aesKey);
log.info("AES加密數(shù)據(jù)操作: \nAES加密之前的數(shù)據(jù) = {} \nAES加密之后的數(shù)據(jù) cnotallow= {}",contentJson,content);
//RSA 加密AES密鑰
byte[] bytes = RSAUtil.encryptByPublicKey(aesKey.getBytes("UTF-8"), publicKey, RSAUtil.MAX_ENCRYPT_BLOCK);
String encryptAesKey = RSAUtil.toHexString(bytes);
log.info("RSA加密AES密鑰操作: \nRSA加密之前的AES密鑰= {} \nRSA加密之后的AES密鑰 aesKey={}",aesKey,encryptAesKey);
/**
* 09:08:42.376 [main] INFO com.example.api_security_demo.utils.UtilsTestClass - AES加密數(shù)據(jù)操作:
* AES加密之前的數(shù)據(jù) = {"sex":"男","name":"張三","id":15,"age":20}
* AES加密之后的數(shù)據(jù) cnotallow= u/vRpwktLAo12ATyfa1rb14EHNftHfvhYEfy7r+DOJzO6jzXS4bwUJ0xNY8RJu8f
* 09:08:42.380 [main] INFO com.example.api_security_demo.utils.UtilsTestClass - RSA加密AES密鑰操作:
* RSA加密之前的AES密鑰= 9raG41FIE8uK7l3k
* RSA加密之后的AES密鑰 aesKey=c7eccef1d112075ee64eec65163b8b1dcb1a54ea6c8b51875174f6d34fc4ac7d50d2977b7519d275ee610d717d594228e132b053a70cdad9f925701a728ed794684d12097cfb8bea598c561393cb69de384b2ec83aa8ddb9a98a5adb3ed51ee1b9aaab2cf7bc5b49712a95e40ac4ea17421f5250d34b8e629e58db0b26e54b39
* */
}
/**
* Description: Get請求加密傳輸,請求體RequestParameter數(shù)據(jù)封裝測試
* 注意: 通過AES加密之后的數(shù)據(jù) byte[] 需要轉(zhuǎn)換為 HexString十六進(jìn)制字符串后才能在 請求地址中傳輸,不能在用Base64編碼格式的方式進(jìn)行傳輸!
*/
@Test
public void getRequestBodyEncryptTest() throws Exception {
//自定義方式獲取 aesKey
String aesKey = AESUtil.getAESKey(16);
//內(nèi)部方式獲取 Base64AesKey
String base64AesKey = AESUtil.generateRandomAesKeyWithBase64();
//創(chuàng)建請求體body數(shù)據(jù) content
//模擬業(yè)務(wù)數(shù)據(jù)Json,并用AES密鑰Key進(jìn)行加密
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", 15);
dataMap.put("name", "張三");
dataMap.put("sex", "男");
dataMap.put("age", 20);
JSONObject dataJson = new JSONObject(dataMap);
String contentJson = JSONObject.toJSONString(dataJson);
//AES 加密業(yè)務(wù)數(shù)據(jù)
byte[] contentByte = AESUtil.encrypt(contentJson.getBytes("UTF-8"), aesKey.getBytes("UTF-8"));
String content = AESUtil.toHexString(contentByte);
log.info("AES加密數(shù)據(jù)操作: \nAES加密之前的數(shù)據(jù) = {} \nAES加密之后的Byte[]數(shù)據(jù) = {} \nAES加密后的數(shù)據(jù)轉(zhuǎn)換為HexString十六進(jìn)制字符串?dāng)?shù)據(jù)encryptData={}",contentJson,Arrays.toString(contentByte),content);
//RSA 加密AES密鑰
byte[] bytes = RSAUtil.encryptByPublicKey(aesKey.getBytes("UTF-8"), publicKey, RSAUtil.MAX_ENCRYPT_BLOCK);
String encryptAesKey = RSAUtil.toHexString(bytes);
log.info("RSA加密AES密鑰操作: \nRSA加密之前的AES密鑰= {} \nRSA加密之后的AES密鑰aesKey={}",aesKey,encryptAesKey);
/**
* 09:09:13.172 [main] INFO com.example.api_security_demo.utils.UtilsTestClass - AES加密數(shù)據(jù)操作:
* AES加密之前的數(shù)據(jù) = {"sex":"男","name":"張三","id":15,"age":20}
* AES加密之后的Byte[]數(shù)據(jù) = [73, 19, 107, 60, 29, 109, 100, 119, -81, -117, -84, -85, 19, 28, 86, 18, 123, 48, 58, 37, -28, -65, -93, -124, -50, 89, -10, -101, 48, 48, -104, -18, -109, 127, -19, 80, 62, -122, -80, -122, 94, 72, -16, -89, -1, -128, 22, -92]
* AES加密后的數(shù)據(jù)轉(zhuǎn)換為HexString十六進(jìn)制字符串?dāng)?shù)據(jù)encryptData=49136b3c1d6d6477af8bacab131c56127b303a25e4bfa384ce59f69b303098ee937fed503e86b0865e48f0a7ff8016a4
* 09:09:13.177 [main] INFO com.example.api_security_demo.utils.UtilsTestClass - RSA加密AES密鑰操作:
* RSA加密之前的AES密鑰= 868E9FMA727S9W5q
* RSA加密之后的AES密鑰aesKey=2ab5531c7814201b4eaef3802ca883e79ffffd4c4ec32e698403189c0954718fd5cebd0ac5e66e856ec4f95a408442fc76276586a8fdb94c14c8f311f30ad061d6928315078736e6633113cdba255870a78e9077b2f18bdc4b2730804e5d6181df4b0ecf51597f71c8e0ccb89a5e160f1216a7bde5386b42171577db400d5a54
* */
}
@Test
public void testByteBase64String(){
/*
* 創(chuàng)建字節(jié)數(shù)組的方式
* */
byte[] testBytes = new byte[]{0,1,2,3,4};
/*
* 讀取字節(jié)數(shù)組的方式:
* */
System.out.println("Arrays.toString(bytes1) = " + Arrays.toString(testBytes));
//模擬業(yè)務(wù)數(shù)據(jù)Json,并用AES密鑰Key進(jìn)行加密
Map<String, String> dataMap = new HashMap<>(2);
dataMap.put("name", "張三");
dataMap.put("age", "20");
JSONObject dataJson = new JSONObject(dataMap);
String jsonStr = JSONObject.toJSONString(dataJson);
com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
try {
Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);
System.out.println("map.toString() = " + map.toString());
System.out.println("map.get(\"name\") = " + map.get("name"));
System.out.println("map.get(\"age\") = " + map.get("age"));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
byte[] jsonByte = dataJson.toString().getBytes();
System.out.println("new String(jsonByte) = " + new String(jsonByte));
//[兩種方式不一樣!]
String hexStr = "0123456789abcdef";
System.out.println("Arrays.toString(hexStr.getBytes()) = " + Arrays.toString(hexStr.getBytes()));
System.out.println("Arrays.toString(RSAUtil.toBytes(hexStr)) = " + Arrays.toString(RSAUtil.toBytes(hexStr)));
}
/**
* Description: 解密操作測試
*/
@Test
public void testAesDecrypt() throws Exception {
String encryptAesKey = "868dbf00b6849a1189f186f18bc98eca65981829e12d3bad21f4a64c139a6fe6953729e488af642cb5bf7104459a4fbf084bb536f251e2d9fa39747037715da6a73caf23e1d68bd5338d51dd207ebe9c4a72749d87d73eb96fc193adac45e6b8b6b7fcc211ee47efd0d54ea97dcfdbc221ac0bd7664d32becbdd654c3d9b2446";
String encryptDate = "8ee240b806a571f0f7ef5568d9cf5e36d999686acabfa4d5425d73ef7e546c8c1e9147c084269a6884cfeebf6759bd60";
//解密之后的AesKey 56X8817GRC2p33w0
byte[] decryptAesKey = RSAUtil.decryptByPrivateKey(RSAUtil.toBytes(encryptAesKey), privateKey, RSAUtil.MAX_DECRYPT_BLOCK);
String decryptAesKeyStr = new String(decryptAesKey, "UTF-8");
System.out.println("decryptAesKeyStr = " + decryptAesKeyStr);
//GET請求數(shù)據(jù)解密 [加密數(shù)據(jù)為HexStr十六進(jìn)制字符串形式]
byte[] encryptDataByte = AESUtil.toBytes(encryptDate);
System.out.println("Arrays.toString(encryptDataByte) 加密數(shù)據(jù)Byte[]形式 = " + Arrays.toString(encryptDataByte));
String decryptData = new String(AESUtil.decrypt(encryptDataByte,decryptAesKeyStr.getBytes("UTF-8")),"UTF-8");
System.out.println("decryptData解密后的數(shù)據(jù) = " + decryptData);
/* //POST請求數(shù)據(jù)解密 [加密數(shù)據(jù)為Base64編碼格式]
String decryptData2 = AESUtil.decryptFromBase64(encryptDate, decryptAesKeyStr);
System.out.println("decryptData2 解密后的數(shù)據(jù) = " + decryptData2);*/
/**
* AES加密之前的數(shù)據(jù) = {"sex":"男","name":"張三","id":15,"age":20}
* AES加密之后的Byte[]數(shù)據(jù) = [-114, -30, 64, -72, 6, -91, 113, -16, -9, -17, 85, 104, -39, -49, 94, 54, -39, -103, 104, 106, -54, -65, -92, -43, 66, 93, 115, -17, 126, 84, 108, -116, 30, -111, 71, -64, -124, 38, -102, 104, -124, -49, -18, -65, 103, 89, -67, 96]
* AES加密后的數(shù)據(jù)轉(zhuǎn)換為HexString十六進(jìn)制字符串?dāng)?shù)據(jù)encryptData=8ee240b806a571f0f7ef5568d9cf5e36d999686acabfa4d5425d73ef7e546c8c1e9147c084269a6884cfeebf6759bd60
* 16:48:25.095 [main] INFO com.example.api_security_demo.utils.UtilsTestClass - RSA加密AES密鑰操作:
* RSA加密之前的AES密鑰= 8c0N9032214LJ139
* RSA加密之后的AES密鑰aesKey=868dbf00b6849a1189f186f18bc98eca65981829e12d3bad21f4a64c139a6fe6953729e488af642cb5bf7104459a4fbf084bb536f251e2d9fa39747037715da6a73caf23e1d68bd5338d51dd207ebe9c4a72749d87d73eb96fc193adac45e6b8b6b7fcc211ee47efd0d54ea97dcfdbc221ac0bd7664d32becbdd654c3d9b2446
* */
}
/**
* Description: 響應(yīng)數(shù)據(jù)加密后,模擬前端進(jìn)行解密操作
*/
@Test
public void responseEncryptToDecrypt() throws UnsupportedEncodingException {
String aesKeyPost = "9raG41FIE8uK7l3k";
String aesKeyGet = "0303F71572405EF1";
String encryptData = "cf156ddc9cd9fde2a8287fa3b8eadca258ce063130d29d7d9c1b949a4628c42e497b4e1db76244bdd075cb37b8ef0212";
//解密后的數(shù)據(jù)
String decryptData = "";
//Base64編碼格式的數(shù)據(jù)解密
//decryptData = AESUtil.decryptFromBase64(encryptData, aesKeyGet);
//HexString格式的數(shù)據(jù)轉(zhuǎn)換后在解密
byte[] decrypt = AESUtil.decrypt(AESUtil.toBytes(encryptData), aesKeyGet.getBytes("UTF-8"));
decryptData = new String(decrypt, "UTF-8");
System.out.println("decryptData = " + decryptData);
}
}
4.4 模擬加密請求調(diào)用接口
4.4.1 Post請求的封裝
請求頭中封裝數(shù)據(jù):
aksEncrypt: true 開啟解密功能
圖片
請求體Body(application/json格式)的封裝:
- content:通過隨機(jī)AES密鑰加密后的請求數(shù)據(jù)
- aesKey: 通過RSA加密后的隨機(jī)AES密鑰
圖片
Post請求后響應(yīng)數(shù)據(jù)
可以看出 請求數(shù)據(jù)解密后,通過 RequestWrapper重新封裝后的請求數(shù)據(jù),能直接通過@RequestBody 等注解直接獲取到相請求體中的數(shù)據(jù)。 同時(shí)也可以通過 request.getParameter()中存放的參數(shù)。
圖片
4.4.2 Get請求的封裝
Get請求的封裝
圖片
Get請求響應(yīng)結(jié)果:
圖片
可以看出 請求數(shù)據(jù)解密后,通過 RequestWrapper重新封裝后的請求數(shù)據(jù),能直接通過@RequestParam等注解直接獲取到Get請求中的數(shù)據(jù)。 同時(shí)也可以通過 request.getParameter()中存放的參數(shù)。