学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密
前言:
为了提高安全性采用了RSA,但是为了解决RSA加解密性能问题,所以采用了RSA(非对称)+AES(对称加密)方式,如果只考虑其中一种的,可以去看我前面两篇文章,专门单独写的demo,可以自行整合在项目中
大致思路:
- 客户端启动,发送请求到服务端,服务端用RSA算法生成一对公钥和私钥,我们简称为pubkey1,prikey1,将公钥pubkey1返回给客户端。
- 客户端拿到服务端返回的公钥pubkey1后,自己用RSA算法生成一对公钥和私钥,我们简称为pubkey2,prikey2,并将公钥pubkey2通过公钥pubkey1加密,加密之后传输给服务端。
- 此时服务端收到客户端传输的密文,用私钥prikey1进行解密,因为数据是用公钥pubkey1加密的,通过解密就可以得到客户端生成的公钥pubkey2
- 然后自己在生成对称加密,也就是我们的AES,其实也就是相对于我们配置中的那个16的长度的加密key,生成了这个key之后我们就用公钥pubkey2进行加密,返回给客户端,因为只有客户端有pubkey2对应的私钥prikey2,只有客户端才能解密,客户端得到数据之后,用prikey2进行解密操作,得到AES的加密key,最后就用加密key进行数据传输的加密,至此整个流程结束。
具体实践(前端请求加密,服务端解密,服务端响应加密,前端解密):
1.创建spring boot项目,导入相关依赖,
2.编写RSA加解密工具类,AES加解密工具类
3.编写自定义注解(让加解密细粒度)
4.编写自定义DecodeRequestAdvice和EncodeResponseAdvice
5.创建controller
6.创建jsp或者html,引入js(加密和解密的通用js),还有配置,配置文件
ps:因为这里没https证书,所有使用http, 考虑到前后端分离,使用json来传递数据,
第一步:创建spring boot项目过程省略,相关依赖:
-
<!-- WEB依赖 -->
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-web</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-test</artifactId>
-
<scope>test</scope>
-
</dependency>
-
<!-- 热部署依赖 -->
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-devtools</artifactId>
-
<optional>true</optional>
-
</dependency>
-
<!-- mysql的依赖-->
-
<dependency>
-
<groupId>mysql</groupId>
-
<artifactId>mysql-connector-java</artifactId>
-
<scope>runtime</scope>
-
</dependency>
-
<!-- get/set依赖 -->
-
<dependency>
-
<groupId>org.projectlombok</groupId>
-
<artifactId>lombok</artifactId>
-
<version>1.16.20</version>
-
</dependency>
-
<!-- 日志依赖 -->
-
<dependency>
-
<groupId>org.slf4j</groupId>
-
<artifactId>log4j-over-slf4j</artifactId>
-
</dependency>
-
<!-- 阿里巴巴druid数据源依赖 -->
-
<dependency>
-
<groupId>com.alibaba</groupId>
-
<artifactId>druid</artifactId>
-
<version>1.1.12</version>
-
</dependency>
-
<!-- Base64编码需要 -->
-
<dependency>
-
<groupId>org.apache.directory.studio</groupId>
-
<artifactId>org.apache.commons.codec</artifactId>
-
<version>1.8</version>
-
</dependency>
-
<!-- 阿里巴巴fastjson依赖 -->
-
<dependency>
-
<groupId>com.alibaba</groupId>
-
<artifactId>fastjson</artifactId>
-
<version>1.2.47</version>
-
</dependency>
-
<!-- 谷歌gson依赖 -->
-
<dependency>
-
<groupId>com.google.code.gson</groupId>
-
<artifactId>gson</artifactId>
-
<version>2.8.2</version>
-
</dependency>
-
<!-- 工具包依赖 -->
-
<dependency>
-
<groupId>org.apache.commons</groupId>
-
<artifactId>commons-lang3</artifactId>
-
<version>3.4</version>
-
</dependency>
-
<dependency>
-
<groupId>commons-io</groupId>
-
<artifactId>commons-io</artifactId>
-
<version>2.4</version>
-
</dependency>
-
<!-- 使用jasper引擎解析jsp -->
-
<dependency>
-
<groupId>org.apache.tomcat.embed</groupId>
-
<artifactId>tomcat-embed-jasper</artifactId>
-
<scope>provided</scope>
-
</dependency>
-
<!-- jsp标签库 -->
-
<dependency>
-
<groupId>javax.servlet</groupId>
-
<artifactId>jstl</artifactId>
-
</dependency>
-
<!-- servlet 依赖 -->
-
<dependency>
-
<groupId>javax.servlet</groupId>
-
<artifactId>javax.servlet-api</artifactId>
-
<scope>provided</scope>
-
</dependency>
-
<!-- 模板引擎依赖 -->
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-thymeleaf</artifactId>
-
</dependency>
第二步:
-
import javax.crypto.Cipher;
-
import javax.crypto.KeyGenerator;
-
import javax.crypto.spec.SecretKeySpec;
-
-
import org.apache.commons.codec.binary.Base64;
-
-
-
/**
-
* 前后端数据传输加密工具类
-
* @author monkey
-
*
-
*/
-
public class AesEncryptUtils {
-
-
//参数分别代表 算法名称/加密模式/数据填充方式
-
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
-
-
/**
-
* 加密
-
* @param content 加密的字符串
-
* @param encryptKey key值
-
* @return
-
* @throws Exception
-
*/
-
public static String encrypt(String content, String encryptKey) throws Exception {
-
KeyGenerator kgen = KeyGenerator.getInstance("AES");
-
kgen.init(128);
-
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
-
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
-
byte[] b = cipher.doFinal(content.getBytes("utf-8"));
-
// 采用base64算法进行转码,避免出现中文乱码
-
return Base64.encodeBase64String(b);
-
-
}
-
-
/**
-
* 解密
-
* @param encryptStr 解密的字符串
-
* @param decryptKey 解密的key值
-
* @return
-
* @throws Exception
-
*/
-
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
-
KeyGenerator kgen = KeyGenerator.getInstance("AES");
-
kgen.init(128);
-
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
-
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
-
// 采用base64算法进行转码,避免出现中文乱码
-
byte[] encryptBytes = Base64.decodeBase64(encryptStr);
-
byte[] decryptBytes = cipher.doFinal(encryptBytes);
-
return new String(decryptBytes);
-
}
-
}
-
import org.apache.commons.codec.binary.Base64;
-
-
import java.io.ByteArrayOutputStream;
-
import java.security.Key;
-
import java.security.KeyFactory;
-
import java.security.KeyPair;
-
import java.security.KeyPairGenerator;
-
import java.security.PrivateKey;
-
import java.security.PublicKey;
-
import java.security.Signature;
-
import java.security.interfaces.RSAPrivateKey;
-
import java.security.interfaces.RSAPublicKey;
-
import java.security.spec.PKCS8EncodedKeySpec;
-
import java.security.spec.X509EncodedKeySpec;
-
import java.util.HashMap;
-
import java.util.Map;
-
-
import javax.crypto.Cipher;
-
-
/** */
-
/**
-
* <p>
-
* RSA公钥/私钥/签名工具包
-
* </p>
-
* <p>
-
* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
-
* </p>
-
* <p>
-
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
-
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
-
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
-
* </p>
-
*
-
* @author monkey
-
* @date 2018-10-29
-
*/
-
public class RSAUtils {
-
-
/** */
-
/**
-
* 加密算法RSA
-
*/
-
public static final String KEY_ALGORITHM = "RSA";
-
-
/** */
-
/**
-
* 签名算法
-
*/
-
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
-
-
/** */
-
/**
-
* 获取公钥的key
-
*/
-
private static final String PUBLIC_KEY = "RSAPublicKey";
-
-
/** */
-
/**
-
* 获取私钥的key
-
*/
-
private static final String PRIVATE_KEY = "RSAPrivateKey";
-
-
/** */
-
/**
-
* RSA最大加密明文大小
-
*/
-
private static final int MAX_ENCRYPT_BLOCK = 117;
-
-
/** */
-
/**
-
* RSA最大解密密文大小
-
*/
-
private static final int MAX_DECRYPT_BLOCK = 128;
-
-
/** */
-
/**
-
* RSA 位数 如果采用2048 上面最大加密和最大解密则须填写: 245 256
-
*/
-
private static final int INITIALIZE_LENGTH = 1024;
-
-
/** */
-
/**
-
* <p>
-
* 生成密钥对(公钥和私钥)
-
* </p>
-
*
-
* @return
-
* @throws Exception
-
*/
-
public static Map<String, Object> genKeyPair() throws Exception {
-
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
-
keyPairGen.initialize(INITIALIZE_LENGTH);
-
KeyPair keyPair = keyPairGen.generateKeyPair();
-
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
-
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
-
Map<String, Object> keyMap = new HashMap<String, Object>(2);
-
keyMap.put(PUBLIC_KEY, publicKey);
-
keyMap.put(PRIVATE_KEY, privateKey);
-
return keyMap;
-
}
-
-
/** */
-
/**
-
* <p>
-
* 用私钥对信息生成数字签名
-
* </p>
-
*
-
* @param data
-
* 已加密数据
-
* @param privateKey
-
* 私钥(BASE64编码)
-
*
-
* @return
-
* @throws Exception
-
*/
-
public static String sign(byte[] data, String privateKey) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(privateKey);
-
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
-
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
-
signature.initSign(privateK);
-
signature.update(data);
-
return Base64.encodeBase64String(signature.sign());
-
}
-
-
/** */
-
/**
-
* <p>
-
* 校验数字签名
-
* </p>
-
*
-
* @param data
-
* 已加密数据
-
* @param publicKey
-
* 公钥(BASE64编码)
-
* @param sign
-
* 数字签名
-
*
-
* @return
-
* @throws Exception
-
*
-
*/
-
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(publicKey);
-
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
PublicKey publicK = keyFactory.generatePublic(keySpec);
-
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
-
signature.initVerify(publicK);
-
signature.update(data);
-
return signature.verify(Base64.decodeBase64(sign));
-
}
-
-
/** */
-
/**
-
* <P>
-
* 私钥解密
-
* </p>
-
*
-
* @param encryptedData
-
* 已加密数据
-
* @param privateKey
-
* 私钥(BASE64编码)
-
* @return
-
* @throws Exception
-
*/
-
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(privateKey);
-
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
-
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
-
cipher.init(Cipher.DECRYPT_MODE, privateK);
-
int inputLen = encryptedData.length;
-
ByteArrayOutputStream out = new ByteArrayOutputStream();
-
int offSet = 0;
-
byte[] cache;
-
int i = 0;
-
// 对数据分段解密
-
while (inputLen - offSet > 0) {
-
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
-
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
-
} else {
-
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
-
}
-
out.write(cache, 0, cache.length);
-
i++;
-
offSet = i * MAX_DECRYPT_BLOCK;
-
}
-
byte[] decryptedData = out.toByteArray();
-
out.close();
-
return decryptedData;
-
}
-
-
/** */
-
/**
-
* <p>
-
* 公钥解密
-
* </p>
-
*
-
* @param encryptedData
-
* 已加密数据
-
* @param publicKey
-
* 公钥(BASE64编码)
-
* @return
-
* @throws Exception
-
*/
-
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(publicKey);
-
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
Key publicK = keyFactory.generatePublic(x509KeySpec);
-
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
-
cipher.init(Cipher.DECRYPT_MODE, publicK);
-
int inputLen = encryptedData.length;
-
ByteArrayOutputStream out = new ByteArrayOutputStream();
-
int offSet = 0;
-
byte[] cache;
-
int i = 0;
-
// 对数据分段解密
-
while (inputLen - offSet > 0) {
-
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
-
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
-
} else {
-
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
-
}
-
out.write(cache, 0, cache.length);
-
i++;
-
offSet = i * MAX_DECRYPT_BLOCK;
-
}
-
byte[] decryptedData = out.toByteArray();
-
out.close();
-
return decryptedData;
-
}
-
-
/** */
-
/**
-
* <p>
-
* 公钥加密
-
* </p>
-
*
-
* @param data
-
* 源数据
-
* @param publicKey
-
* 公钥(BASE64编码)
-
* @return
-
* @throws Exception
-
*/
-
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(publicKey);
-
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
Key publicK = keyFactory.generatePublic(x509KeySpec);
-
// 对数据加密
-
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
-
cipher.init(Cipher.ENCRYPT_MODE, publicK);
-
int inputLen = data.length;
-
ByteArrayOutputStream out = new ByteArrayOutputStream();
-
int offSet = 0;
-
byte[] cache;
-
int i = 0;
-
// 对数据分段加密
-
while (inputLen - offSet > 0) {
-
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
-
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
-
} else {
-
cache = cipher.doFinal(data, offSet, inputLen - offSet);
-
}
-
out.write(cache, 0, cache.length);
-
i++;
-
offSet = i * MAX_ENCRYPT_BLOCK;
-
}
-
byte[] encryptedData = out.toByteArray();
-
out.close();
-
return encryptedData;
-
}
-
-
/** */
-
/**
-
* <p>
-
* 私钥加密
-
* </p>
-
*
-
* @param data
-
* 源数据
-
* @param privateKey
-
* 私钥(BASE64编码)
-
* @return
-
* @throws Exception
-
*/
-
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
-
byte[] keyBytes = Base64.decodeBase64(privateKey);
-
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
-
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
-
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
-
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
-
cipher.init(Cipher.ENCRYPT_MODE, privateK);
-
int inputLen = data.length;
-
ByteArrayOutputStream out = new ByteArrayOutputStream();
-
int offSet = 0;
-
byte[] cache;
-
int i = 0;
-
// 对数据分段加密
-
while (inputLen - offSet > 0) {
-
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
-
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
-
} else {
-
cache = cipher.doFinal(data, offSet, inputLen - offSet);
-
}
-
out.write(cache, 0, cache.length);
-
i++;
-
offSet = i * MAX_ENCRYPT_BLOCK;
-
}
-
byte[] encryptedData = out.toByteArray();
-
out.close();
-
return encryptedData;
-
}
-
-
/** */
-
/**
-
* <p>
-
* 获取私钥
-
* </p>
-
*
-
* @param keyMap
-
* 密钥对
-
* @return
-
* @throws Exception
-
*/
-
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
-
Key key = (Key) keyMap.get(PRIVATE_KEY);
-
return Base64.encodeBase64String(key.getEncoded());
-
}
-
-
/** */
-
/**
-
* <p>
-
* 获取公钥
-
* </p>
-
*
-
* @param keyMap
-
* 密钥对
-
* @return
-
* @throws Exception
-
*/
-
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
-
Key key = (Key) keyMap.get(PUBLIC_KEY);
-
return Base64.encodeBase64String(key.getEncoded());
-
}
-
-
/**
-
* java端公钥加密
-
*/
-
public static String encryptedDataOnJava(String data, String PUBLICKEY) {
-
try {
-
data = Base64.encodeBase64String(encryptByPublicKey(data.getBytes(), PUBLICKEY));
-
} catch (Exception e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
return data;
-
}
-
-
/**
-
* java端私钥解密
-
*/
-
public static String decryptDataOnJava(String data, String PRIVATEKEY) {
-
String temp = "";
-
try {
-
byte[] rs = Base64.decodeBase64(data);
-
temp = new String(RSAUtils.decryptByPrivateKey(rs, PRIVATEKEY),"UTF-8");
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
return temp;
-
}
第三步:
-
import org.springframework.web.bind.annotation.Mapping;
-
-
import java.lang.annotation.*;
-
-
-
/**
-
* @author monkey
-
* @desc 请求数据解密
-
* @date 2018/10/25 20:17
-
*/
-
@Target({ElementType.METHOD,ElementType.TYPE})
-
@Retention(RetentionPolicy.RUNTIME)
-
@Mapping
-
@Documented
-
public @interface SecurityParameter {
-
-
/**
-
* 入参是否解密,默认解密
-
*/
-
boolean inDecode() default true;
-
-
/**
-
* 出参是否加密,默认加密
-
*/
-
boolean outEncode() default true;
-
}
第四步:
-
import com.google.gson.Gson;
-
import com.google.gson.reflect.TypeToken;
-
import com.monkey.springboot.demo.annotation.SecurityParameter;
-
import com.monkey.springboot.demo.utils.AesEncryptUtils;
-
import com.monkey.springboot.demo.utils.RSAUtils;
-
import org.apache.commons.io.IOUtils;
-
import org.apache.commons.lang3.StringUtils;
-
import org.slf4j.Logger;
-
import org.slf4j.LoggerFactory;
-
import org.springframework.beans.factory.annotation.Value;
-
import org.springframework.core.MethodParameter;
-
import org.springframework.http.HttpHeaders;
-
import org.springframework.http.HttpInputMessage;
-
import org.springframework.http.converter.HttpMessageConverter;
-
import org.springframework.web.bind.annotation.ControllerAdvice;
-
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
-
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.lang.reflect.Type;
-
import java.util.Map;
-
-
/**
-
* @author monkey
-
* @desc 请求数据解密
-
* @date 2018/10/29 20:17
-
*/
-
@ControllerAdvice(basePackages = "com.monkey.springboot.demo.controller")
-
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {
-
-
private static final Logger logger = LoggerFactory.getLogger(DecodeRequestBodyAdvice.class);
-
-
@Value("${server.private.key}")
-
private String SERVER_PRIVATE_KEY;
-
//private static final String SERVER_PRIVATE_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";
-
-
@Override
-
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
-
return true;
-
}
-
-
@Override
-
public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
-
return body;
-
}
-
-
@Override
-
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
-
try {
-
boolean encode = false;
-
if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
-
//获取注解配置的包含和去除字段
-
SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
-
//入参是否需要解密
-
encode = serializedField.inDecode();
-
}
-
if (encode) {
-
logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
-
return new MyHttpInputMessage(inputMessage);
-
}else{
-
return inputMessage;
-
}
-
} catch (Exception e) {
-
e.printStackTrace();
-
logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:"+e.getMessage());
-
return inputMessage;
-
}
-
}
-
-
@Override
-
public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
-
return body;
-
}
-
-
class MyHttpInputMessage implements HttpInputMessage {
-
private HttpHeaders headers;
-
-
private InputStream body;
-
-
public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
-
this.headers = inputMessage.getHeaders();
-
this.body = IOUtils.toInputStream(easpString(IOUtils.toString(inputMessage.getBody(),"utf-8")));
-
}
-
-
@Override
-
public InputStream getBody() throws IOException {
-
return body;
-
}
-
-
@Override
-
public HttpHeaders getHeaders() {
-
return headers;
-
}
-
-
/**
-
*
-
* @param requestData
-
* @return
-
*/
-
public String easpString(String requestData) {
-
if(requestData != null && !requestData.equals("")){
-
Map<String,String> map = new Gson().fromJson(requestData,new TypeToken<Map<String,String>>() {
-
}.getType());
-
// 密文
-
String data = map.get("requestData");
-
// 加密的ase秘钥
-
String encrypted = map.get("encrypted");
-
if(StringUtils.isEmpty(data) || StringUtils.isEmpty(encrypted)){
-
throw new RuntimeException("参数【requestData】缺失异常!");
-
}else{
-
String content = null ;
-
String aseKey = null;
-
try {
-
aseKey = RSAUtils.decryptDataOnJava(encrypted,SERVER_PRIVATE_KEY);
-
}catch (Exception e){
-
throw new RuntimeException("参数【aseKey】解析异常!");
-
}
-
try {
-
content = AesEncryptUtils.decrypt(data, aseKey);
-
}catch (Exception e){
-
throw new RuntimeException("参数【content】解析异常!");
-
}
-
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(aseKey)){
-
throw new RuntimeException("参数【requestData】解析参数空指针异常!");
-
}
-
return content;
-
}
-
}
-
throw new RuntimeException("参数【requestData】不合法异常!");
-
}
-
}
-
}
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
import com.monkey.springboot.demo.annotation.SecurityParameter;
-
import com.monkey.springboot.demo.utils.AesEncryptUtils;
-
import com.monkey.springboot.demo.utils.RSAUtils;
-
import org.slf4j.Logger;
-
import org.slf4j.LoggerFactory;
-
import org.springframework.beans.factory.annotation.Value;
-
import org.springframework.core.MethodParameter;
-
import org.springframework.http.MediaType;
-
import org.springframework.http.server.ServerHttpRequest;
-
import org.springframework.http.server.ServerHttpResponse;
-
import org.springframework.web.bind.annotation.ControllerAdvice;
-
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
-
-
import java.util.HashMap;
-
import java.util.Map;
-
import java.util.Random;
-
-
/**
-
* @author monkey
-
* @desc 返回数据加密
-
* @date 2018/10/25 20:17
-
*/
-
@ControllerAdvice(basePackages = "com.monkey.springboot.demo.controller")
-
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice {
-
-
private final static Logger logger = LoggerFactory.getLogger(EncodeResponseBodyAdvice.class);
-
-
@Value("${client.public.key}")
-
private String CLIENT_PUBLIC_KEY;
-
//private static final String CLIENT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9ikrLxa/cgLZXQugBQFhdxCPQmEZ9j9hadra81MqAxmRkc3eFwROAHk/+39fhmDwgtjE/w4cO6XDabL/mi5V37ioByS1QpovF8ZlJgz/RjvV3TEanvxluridXlNTfOd45uC9+TmR2DzRk5p25U1F74wF7K2KSGv2gyqZvttxrfwIDAQAB";
-
-
@Override
-
public boolean supports(MethodParameter methodParameter, Class aClass) {
-
return true;
-
}
-
-
@Override
-
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
-
boolean encode = false;
-
if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
-
//获取注解配置的包含和去除字段
-
SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
-
//出参是否需要加密
-
encode = serializedField.outEncode();
-
}
-
if (encode) {
-
logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
-
ObjectMapper objectMapper = new ObjectMapper();
-
try {
-
String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
-
// 生成aes秘钥
-
String aseKey = getRandomString(16);
-
// rsa加密
-
String encrypted = RSAUtils.encryptedDataOnJava(aseKey, CLIENT_PUBLIC_KEY);
-
// aes加密
-
String requestData = AesEncryptUtils.encrypt(result, aseKey);
-
Map<String, String> map = new HashMap<>();
-
map.put("encrypted", encrypted);
-
map.put("requestData", requestData);
-
return map;
-
} catch (Exception e) {
-
e.printStackTrace();
-
logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());
-
}
-
}
-
return body;
-
}
-
-
/**
-
* 创建指定位数的随机字符串
-
* @param length 表示生成字符串的长度
-
* @return 字符串
-
*/
-
public static String getRandomString(int length) {
-
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
-
Random random = new Random();
-
StringBuffer sb = new StringBuffer();
-
for (int i = 0; i < length; i++) {
-
int number = random.nextInt(base.length());
-
sb.append(base.charAt(number));
-
}
-
return sb.toString();
-
}
-
-
}
第五步:
-
/**
-
* 跳转RSA+AES双重加密页面
-
*
-
* @return
-
*/
-
-
@RequestMapping("/test")
-
public String goTest() {
-
return "test";
-
}
-
-
/**
-
* RSA+AES双重加密测试
-
*
-
* @return object
-
*/
-
@RequestMapping("/testEncrypt")
-
@ResponseBody
-
@SecurityParameter
-
public Persion testEncrypt(@RequestBody Persion info) {
-
System.out.println(info.getName());
-
String content = "内容";
-
info.setName(content);
-
return info;
-
}
第六步: 其中random,js(生成一个16位数的随机字符串),是我自己定义的,其余的都可以去官方下载
-
<!DOCTYPE html>
-
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
<head>
-
<meta charset="UTF-8">
-
<title>RSA+AES 加解密</title>
-
<script type="text/javascript" th:src="@{~/js/jquery-2.2.3.min.js}"></script>
-
<script type="text/javascript" th:src="@{~/js/jsencrypt.min.js}"></script>
-
<script type="text/javascript" th:src="@{~/js/aes.js}"></script>
-
<script type="text/javascript" th:src="@{~/js/pad-zeropadding.js}"></script>
-
<script type="text/javascript" th:src="@{~/js/security.js}"></script>
-
<script type="text/javascript" th:src="@{~/js/random.js}"></script>
-
</head>
-
<body>
-
-
<script type="text/javascript">
-
$(function() {
-
$("#bt").click(
-
function() {
-
// 获取16位随机数,当做aes秘钥key
-
var randomStr = randomString(16);
-
// aes加密
-
var data = Encrypt(JSON.stringify({name:"好看"}),randomStr);
-
// rsa加密
-
var encrypt = new JSEncrypt();
-
encrypt.setPublicKey($("#servicePublicKey").val());
-
var encrypted = encrypt.encrypt(randomStr);
-
// 创建json对象
-
var json = {
-
"requestData": data,
-
"encrypted": encrypted
-
};
-
$.ajax({
-
type: "POST",
-
url:"/testEncrypt",
-
data: JSON.stringify(json),
-
dataType:'json',
-
contentType: "application/json",
-
success: function(result) {
-
alert("返回的数据对象:"+result);
-
// rsa解密,获取到aes秘钥
-
var decrypt = new JSEncrypt();
-
decrypt.setPrivateKey($('#clientPrivateKey').val());
-
var aesKey = decrypt.decrypt(result.encrypted);
-
// 用aes秘钥进行解密
-
var resultData = Decrypt(result.requestData,aesKey);
-
alert("解密的数据:" + resultData);
-
}
-
});
-
});
-
});
-
</script>
-
<h2>服务端公钥:</h2>
-
<textarea id="servicePublicKey" rows="5" cols="45">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ9s1qlOyv9qpuaTqauW6fUftzE50rVk3yVPZwv1aO1Ch/XSEz76xCwkyvqpaqceRXrPpdBmO5+ruJ+I8osOHo7L5GWEOcMOO+8izp9hXKBBrmRMD4Egpn00k9DhVIEKp/vyddZPS/doxB8onhN6poTJDLdFLFVEicMf52caN9GQIDAQAB
-
</textarea>
-
<h2>客户端私钥:</h2>
-
<textarea id="clientPrivateKey" rows="5" cols="45">MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL2KSsvFr9yAtldC6AFAWF3EI9CYRn2P2Fp2trzUyoDGZGRzd4XBE4AeT/7f1+GYPCC2MT/Dhw7pcNpsv+aLlXfuKgHJLVCmi8XxmUmDP9GO9XdMRqe/GW6uJ1eU1N853jm4L35OZHYPNGTmnblTUXvjAXsrYpIa/aDKpm+23Gt/AgMBAAECgYBqtFMdWsKBkZiVkZ4JLk9RIl3DTibJA1UawKBpuCX0zzuvbW3JSAQRaX9BjoT7hPe8trUNH6eGFpeo7/Ys9UIEU61c33Q49NBPEVXH2+PhefIE74b8/H9cu1iYQyn9NSGKt0clo5/CU2G3OA7h+xqD9b7ifd4+DtdrS3KDpTPa0QJBAPhBkdpomvIWmUfI69WerwZHrzMZEFYHThG9SbWw0UgIjdKmSiQmrXawPZLe/o3BxPSIIXDzxiVAimdjVJcfC4kCQQDDc9nUvbLt4TryCfnR7x2KECh3BDEv/cuw/e67m0HYOdooV4KQ4aVous/TbbpcyPGcC180XCHjF11gqVa6hdTHAkBpEJcBsDOjMR093DKy/a1lIwFqxri7L+xCZbHES0jHC5e6BtZp5lSTXpMwjV997vvD4bkFbKX3LhFlIAy0yFbBAkAgvjC43gqypS+9yoQKcldtgKV2wsIGuyq7fN7YmPrf4Vk1tutNoC+YqusUDWbSEmu/a3xIhkK7C3f+MIAyASeTAkEA6CalrJUYBeDcaSHKhmJIceQ7baf8Q7uMYY5gRYuQ4rGudcXXaLi+o2I9f9in5qxE/SM/y9LuBmkzrCuy0tlNXA==
-
</textarea>
-
<input type="button" id="bt" value="提交" />
-
</body>
-
</html>
application.properties :
-
server.private.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==
-
client.public.key=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9ikrLxa/cgLZXQugBQFhdxCPQmEZ9j9hadra81MqAxmRkc3eFwROAHk/+39fhmDwgtjE/w4cO6XDabL/mi5V37ioByS1QpovF8ZlJgz/RjvV3TEanvxluridXlNTfOd45uC9+TmR2DzRk5p25U1F74wF7K2KSGv2gyqZvttxrfwIDAQAB
后记:
现在我要把这种混合加密方式,要整合进行到我的项目当中,到时候如果出现一些别的问题,我在更新帖,
---没有绝对安全,只有相对安全!!!!
学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密的更多相关文章
-
Android接口安全 - RSA+AES混合加密方案
转载请注明出处: http://blog.csdn.net/aa464971/article/details/51034462 本文以Androidclient加密提交数据到Java服务端后进行解密为 ...
-
Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档
0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...
-
Spring Boot 学习1-创建Spring Boot应用
如果使用Maven, 确保先安装好Maven再继续. 创建POM文件 在这里有两种方式: 继承Spring Boot parent的pom. 不继承. 继承Spring Boot pom 1 2 3 ...
-
spring boot 之如何在两个页面之间传递值(转)
原文地址:spring boot 之如何在两个页面之间传递值 问题:页面之间的跳转,通常带有值的传输,但是,在现在比较流行的SPRING MVC WEB 开发模型中,设计机制导致页面之间的直接接跳转和 ...
-
spring boot 登录注册 demo (三) -- 前后端传递
前端页面通过thymeleaf渲染 <dependency> <groupId>org.springframework.boot</groupId> <art ...
-
PHP 服务端 和 APP 客户端 实现 RSA+AES 双向加密解密
目的:服务端和移动端双向加密解密 共有七个文件 其中包括三个类文件 lib_aes.php aes对称加密解密类 server_rsa_crypt.php 服务端RSA公钥私钥非对称加密解密类 cli ...
-
spring boot基于DRUID数据源密码加密及数据源监控实现
前言 随着需求和技术的日益革新,spring boot框架是越来越流行,她也越来越多地出现在我们的项目中,当然最主要的原因还是因为spring boot构建项目实在是太爽了,构建方便,开发简单,而且效 ...
-
Spring Boot2 系列教程(二十四)Spring Boot 整合 Jpa
Spring Boot 中的数据持久化方案前面给大伙介绍了两种了,一个是 JdbcTemplate,还有一个 MyBatis,JdbcTemplate 配置简单,使用也简单,但是功能也非常有限,MyB ...
-
【Spring Boot学习之六】Spring Boot整合定时任务&;异步调用
环境 eclipse 4.7 jdk 1.8 Spring Boot 1.5.2一.定时任务1.启动类添加注解@EnableScheduling 用于开启定时任务 package com.wjy; i ...
随机推荐
-
shortcuts on Windows and MacOS
我现在使用Window 10与MacOS,发现各千秋,也发现Window向MacOS学习并借鉴了一些东西. MacOS有一点非常好的地方是,它可以不怎么使用鼠标,而通过TouchPad便可完成.体验起 ...
-
springmvc对同名参数处理-我们到底能走多远系列(44)
springmvc对同名参数处理 扯淡: 中断发博客几个月,其实蛮不爽的,可能最近太忙太劳累了些,很多总结也没时间写,今天刚好遇到个小问题,就阅读下源码找找乐.因为考虑到网上大多是提供解决问题的方案, ...
-
Linux下串口与工业协议的开发
1.串口通信原理 串口通信定义 串口通信:数据的串行传送方式.串口通信可分为同步通信与异步通信. 同步通信:按照软件识别同步字符来实现数据的发送和接收. 将许多字符组成一个信息组进行发送 要求发送时钟 ...
-
Android开发-API指南-<;data>;
<data> 英文原文:http://developer.android.com/guide/topics/manifest/data-element.html 采集(更新)日期:2014 ...
-
android bitmap out of memory总结、心得
setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,这些函数在完成decode后,最终都是通过java层的creat ...
-
[Oracle运维工程师手记] 如何从trace 文件,判断是否执行了并行
[Oracle运维工程师手记系列]如何从trace 文件,判断是否执行了并行 客户说,明明指定了并行的hint,OEM 却报说没有并行,并且提供了画面. 客户的SQL文长这样: INSERT/*+ p ...
-
Docker安装使用battery historian
apt-get insatll docker.io battery historian ubuntu下使用 首先要确保是google浏览器,然后用命令行 google-chrome --proxy-s ...
-
百度云虚拟主机配置 Thinkphp5.1
材料 服务器:百度云虚拟主机(nginx+php7.0+linux) Thinkphp 5.1 问题 百度云默认目录为/webroot,但是我们的需求是将项目存放到/webroot/public下面. ...
-
Houdini技术体系 基础管线(四) :Houdini驱动的UE4植被系统 上篇
背景 之前在<Houdini技术体系 过程化地形系统(一):Far Cry5的植被系统分析>一文中已经对AAA游戏中过程化植被的需求有了一定的定义,后续工作就是如何用Houdini开发功能 ...
-
hdu 4746Mophues[莫比乌斯反演]
Mophues Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 327670/327670 K (Java/Others) Total ...