参数加密是当前比较流行的项目安全保护方式,防止接口被恶意调用。主要是利用RSA或者其他方式生成公钥和私钥。前端使用公钥对参数进行加密生成密文作为新的参数。后台在接收到密文参数后,使用私钥对密文进行解密后在使用明文参数。解密参数可以使用filter对指定请求进行参数解密,也可以在接口里面对参数进行解密。
springboot配置filter过滤器:
1.创建filter类:
import com.hpm.blog.model.Appapk;
import com.hpm.blog.service.AppapkService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
public class KevinTokenFilter implements Filter {
private FilterConfig config;
private AppapkService appapkService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
config = filterConfig;
/**
* 注入AppapkService对象 用户查询数据库
*/
ServletContext sc = filterConfig.getServletContext();
WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
if (cxt != null && cxt.getBean(AppapkService.class) != null && appapkService == null) {
appapkService = (AppapkService) cxt.getBean(AppapkService.class);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//如果这是个http请求
if(request instanceof HttpServletRequest) {
//强转成http请求
HttpServletRequest req1 = (HttpServletRequest) request;
//3.创建LogHttpServletRequestWrapper类继承HttpServletRequestWrapper,并且将http请求 req1放入到创建的LogHttpServletRequestWrapper类中。并且在此类中做解密操作。
LogHttpServletRequestWrapper req = new LogHttpServletRequestWrapper(req1);
Map<String, Object> parameterMap=new LinkedHashMap<>();
String apk = req.getHeader("user-agent");//取出header中的版本信息
int num = apk.indexOf("_");
String apktype = apk.substring(0,num);
String edition = apk.substring(num+1,apk.length());
Appapk appapk = appapkService.queryAppapkbyheader(edition,apktype);
//判断版本信息是否放行
if (null != appapk) {
/*if("GET".equals(req.getMethod())){
parameterMap= JSONUtil.parseObj(ServletUtil.getParams(request));
}else{
parameterMap= JSONUtil.parseObj(req.getBody());
}*/
//放行访问
chain.doFilter(req, response);
} else {
//否则默认访问index接口
// wrapper.sendRedirect("https://www.baidu.com");
req.getRequestDispatcher("/index").forward(request,response);
}
}
// chain.doFilter(request, response);
// HttpServletRequest request, HttpServletResponse response
}
@Override
public void destroy() {
}
}
2.将filter对象放入对象池中:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebComponent2Config {
@Bean
public FilterRegistrationBean someFilterRegistration1() {
//新建过滤器注册类
FilterRegistrationBean registration = new FilterRegistrationBean();
// 添加我们写好的过滤器
registration.setFilter( new KevinTokenFilter());
// 设置过滤器的URL模式
registration.addUrlPatterns("/*");
return registration;
}
}
3. //创建LogHttpServletRequestWrapper类继承HttpServletRequestWrapper
import com.hpm.blog.util.RSAEncrypt;
import net.sf.json.JSONObject;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
public class LogHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public LogHttpServletRequestWrapper(HttpServletRequest request){
super(request);
//创建字符缓冲区
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
InputStream inputStream = null;
try {
inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
//将输入流里面的参数读取到字符缓冲区
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
//s为接口请求参数字符串类型
String s = stringBuilder.toString();
if(!"".equals(s)){
开始解密字符串类型参数
JSONObject json = RSAEncrypt.decryptJson( JSONObject.fromObject(stringBuilder.toString()));
body = json.toString();
}else{
body=s;
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = 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 byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
关于参数加密、解密、生成RSA秘钥的方法:
import com.hpm.blog.model.ReturnResult;
import com.hpm.blog.util.Constants;
import com.hpm.blog.util.RSAEncrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class RsamessageApi {
@RequestMapping("/shengchengmiyao")
public ReturnResult generatersakey(@RequestBody Map<String, String> map) throws Exception {
String message = String.valueOf(map.get("message"));
ReturnResult result = new ReturnResult();
Map keyMap = RSAEncrypt.genKeyPair();
//加密字符串
// String message = "maojungang";
System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = RSAEncrypt.encrypt(message,(String)keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);
String messageDe = RSAEncrypt.decrypt(messageEn,(String)keyMap.get(1));
System.out.println("还原后的字符串为:" + messageDe);
Map Maps = new HashMap();
Maps.put("随机公钥",keyMap.get(0));
Maps.put("随机私钥",keyMap.get(1));
Maps.put("加密字符串","maojungang");
Maps.put("加密后字符串",messageEn);
Maps.put("解密后字符串",messageDe);
result.setData(Maps);
result.setCode("10000");
result.setMessage("查询成功");
return result;
}
@RequestMapping(value = "/jiemi",method = RequestMethod.POST)
public ReturnResult testrsakey(@RequestBody Map<String, String> map) throws Exception {
String messageEn = String.valueOf(map.get("message"));
ReturnResult result = new ReturnResult();
// Map keyMap = RSAEncrypt.genKeyPair();
//加密字符串
// String message = "maojungang";
/*System.out.println("随机生成的公钥为:" + keyMap.get(0));
System.out.println("随机生成的私钥为:" + keyMap.get(1));
String messageEn = RSAEncrypt.encrypt(message,(String)keyMap.get(0));
System.out.println(message + "\t加密后的字符串为:" + messageEn);*/
//Constants.RSAPRIVITEKEY是用上面方法生成的私钥,用解密密文字符串
String messageDe = RSAEncrypt.decrypt(messageEn, Constants.RSAPRIVITEKEY);
System.out.println("还原后的字符串为:" + messageDe);
Map Maps = new HashMap();
Maps.put("加密后字符串",messageEn);
Maps.put("解密后字符串",messageDe);
result.setData(Maps);
result.setCode("10000");
result.setMessage("查询成功");
return result;
}
@RequestMapping(value = "/jiami",method = RequestMethod.POST)
public ReturnResult jiamikey(@RequestBody Map<String, String> map) throws Exception {
String message = String.valueOf(map.get("message"));
ReturnResult result = new ReturnResult();
//Constants.PUBLICKEY是用上面方法生成的公钥,用于前端加密字符串生成密文
String messageEn = RSAEncrypt.encrypt(message,Constants.PUBLICKEY);
System.out.println(message + "\t加密后的字符串为:" + messageEn);
Map Maps = new HashMap();
Maps.put("加密后字符串",messageEn);
result.setData(Maps);
result.setCode("10000");
result.setMessage("查询成功");
return result;
}
}
参数解密封装的工具类:
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
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.HashMap;
import java.util.Map;
public class RSAEncrypt {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static Map genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(0,publicKeyString); //0表示公钥
keyMap.put(1,privateKeyString); //1表示私钥
return keyMap;
}
/**
* RSA公钥加密
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str
* 加密字符串
* @param privateKey
* 私钥
* @return 铭文
* @throws Exception
* 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
public static Map<String, Object> decryptMap(Map<String, Object> map){
for (Map.Entry<String, Object> entry : map.entrySet()) {
entry.setValue(fordecrypt(String.valueOf(entry.getValue())));
}
return map;
}
public static JSONObject decryptJson(JSONObject jsonObject){
Map<String, Object> map = new HashMap<String, Object>();
map.putAll(jsonObject);
for (Map.Entry<String, Object> entry : map.entrySet()) {
entry.setValue(fordecrypt(String.valueOf(entry.getValue())));
}
JSONObject json = JSONObject.fromObject(map);
return json;
}
public static String fordecrypt(String str){
String outStr = "";
try{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(Constants.RSAPRIVITEKEY);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
outStr = new String(cipher.doFinal(inputByte));
}catch (Exception e){
}
return outStr;
}
/**
* 解密算法 cryptograph:密文分段解密
*/
public static String fordecrypts(String str){
/** 将文件中的私钥对象读出 */
String outStr = "";
try{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
byte[] keyBytes = Base64.decodeBase64(Constants.RSAPRIVITEKEY);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = inputByte.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(inputByte, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(inputByte, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
outStr = new String(decryptedData);
out.close();
}catch (Exception e){
outStr="解密失败!";
}
return outStr;
}
}