junit测试 RSA非对称签名和MD5数据签名 java
2017-07-17 10:16
387 查看
junit测试 RSA非对称签名和MD5数据签名 java
-------------------------AbstractTest----start------------------------------
package com;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AbstractTest {
public MockMvc mvc;
public Map<String, Object> baseMap ;
@Autowired
WebApplicationContext wac ;
@Before
public void setup(){
/*
* MockMvcBuilders使用构建MockMvc对象.
*/
baseMap = new HashMap<>() ;
baseMap.put("param1",1);
baseMap.put("param2",1);
baseMap.put("param3","123123213213213213213");
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
}
-------------------------AbstractTest----end------------------------------
-------------------------SignControllerTest----start------------------------------
package com.test.controller;
import java.util.TreeMap;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.alibaba.fastjson.JSONObject;
import com.AbstractTest;
import com.util.StringUtil;
import com.util.sign.RSAUtils;
import com.util.sign.RequestUtils;
public class SignControllerTest extends AbstractTest{
private final static Logger log = LoggerFactory.getLogger(SignControllerTest.class);
@Test
public void testValidSign() throws Exception {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("activityId", "710183692382806016");
params.put("status", "0");
params.put("couponName", "优惠券名称0710001");
params.put("couponType", "1");
params.put("singleAmt", "10");
params.put("amtLimit", "500");
params.put("startTime", "");
params.put("endTime", "");
//mothod 2
//拼接签名原串
String paramSrc = RequestUtils.getParamSrc(params);
log.info("拼接签名原串(paramSrc):" + paramSrc);
// 原串转码,UTF-8转GBK
paramSrc = StringUtil.utf8ToUnicode(paramSrc);
//paramSrc = new String(paramSrc.getBytes(SignConfig.serverEncodeType), SignConfig.serverEncodeType);
log.info("转码后拼接签名串(paramSrc):" + paramSrc);
//md5签名
//String sign = MD5Utils.sign(paramSrc);
//RSA签名
String sign = RSAUtils.sign(paramSrc.getBytes("GBK"));
log.info("生成签名(sign):" + sign);
//rsa加密原串
String encryptSrc = paramSrc + "&sign=" + sign;//加密原串
//rsa密串
String cipherData = RSAUtils.serverPubEncrypt(encryptSrc);
log.info("生成加密数据(cipherData):" + cipherData);
JSONObject param = new JSONObject() ;
param.put("cipherData", cipherData);
String json = param.toString() ;
log.info("json格式参数:" + cipherData);
System.out.println("================================请求开始,入参:"+json);
RequestBuilder request = MockMvcRequestBuilders.post("/sign/validSign")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.header("SESSIONNO", "5qr24lk2k424jk24kj24k24k43")
.content(json) ;
MvcResult mvcResult = mvc.perform(request).andReturn() ;
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
Assert.assertTrue("错误,正确的返回值为200", status == 200);
Assert.assertFalse("错误,正确的返回值为200", status != 200);
System.out.println("返回结果:"+status);
System.out.println(content);
}
}
-------------------------SignControllerTest----end------------------------------
-------------------------SignController----start------------------------------
package com.controller;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.bean.Result;
import com.common.enums.ReturnCodeEnum;
import com.common.sign.RSA;
import com.common.sign.SignConfig;
import com.common.sign.SignCore;
import com.controller.vo.UserCouponVo;
import com.util.StringUtil;
import com.util.sign.RSAUtils;
import com.util.sign.RequestUtils;
@RestController
@RequestMapping("/sign")
public class SignController {
private final static Logger log = LoggerFactory.getLogger(SignController.class);
@RequestMapping(value="/modifyAct",method=RequestMethod.POST)
@ResponseBody
public Result modifyUser(HttpServletRequest request,HttpServletResponse response,@RequestBody UserCouponVo vo){
Map<String, String> params = new HashMap<String, String>();
params.put("activityId", vo.getActivityId());
params.put("status", vo.getStatus());
params.put("couponName", vo.getCouponName());
params.put("couponType", vo.getCouponType());
params.put("singleAmt", vo.getSingleAmt());
params.put("amtLimit", vo.getAmtLimit());
params.put("startTime", vo.getStartTime());
params.put("endTime", vo.getEndTime());
Map<String, String> sParaNew = SignCore.paraFilter(params);
//获取待签名字符串
String preSignStr = SignCore.createLinkString(sParaNew);
log.info("获取待签名字符串:" + preSignStr);
String signStr = "";
if(SignConfig.sign_type.equals("RSA")){
signStr = RSA.sign(preSignStr,SignConfig.private_key, SignConfig.input_charset);
}
if(!StringUtils.isEmpty(vo.getSign()) && !vo.getSign().equals(signStr)){
return new Result(ReturnCodeEnum.FAIL_SIGN.getCode(), ReturnCodeEnum.FAIL_SIGN.getDesc());
}
return new Result(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getDesc());
}
@RequestMapping(value = "/validSign", method = RequestMethod.POST)
@ResponseBody
public Result validSign(HttpServletRequest request,HttpServletResponse response,@RequestBody UserCouponVo vo){
if(StringUtils.isEmpty(vo.getCipherData())){
return new Result(ReturnCodeEnum.SIGN_NULL.getCode(), ReturnCodeEnum.SIGN_NULL.getDesc());
}
log.info("请求参数加密数据串:" + JSON.toJSONString(vo));
//数据解密
String responseData = RSAUtils.serverPriDecrypt(vo.getCipherData());
//封装数据
HashMap<String, String> map = RequestUtils.parseString(responseData);
log.info("验签数据串:source ={}" ,map.get("source"));
try {
//rsa验签
if (RSAUtils.verify(map.get("source"), map.get("sign"))) {
//MD5验签
//if (MD5Utils.verify(map.get("source"), map.get("sign"))) {
log.info("rsa验签,验签结果:通过");
} else {
log.info("rsa验签,验签结果:未通过");
}
} catch (Exception e) {
log.error("验签异常", e);
}
log.info("解密后的请求参数数据:map={}",JSON.toJSONString(map));
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
Map<String, String> paramMap = new HashMap<>();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
paramMap.put(entry.getKey(), StringUtil.unicodeToUtf8(entry.getValue()));
}
log.info("解密并转码后的数据:map={}",JSON.toJSONString(paramMap));
return new Result(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getDesc(),paramMap);
}
}
-------------------------SignController---end------------------------------
-------------------------base64----start------------------------------
public final class Base64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets);
}
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
if (fDebug) {
System.out.println("val2 = " + val2);
System.out.println("k4 = " + (k << 4));
System.out.println("vak = " + (val2 | (k << 4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
// if (len % FOURBYTE != 0) {
// return null;// should be divisible by four
// }
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
return null;
} // if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0) // last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0) // last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
-------------------------base64----end------------------------------
-------------------------MD5----start------------------------------
package com.util.sign;
import java.security.MessageDigest;
import com.util.GetParamConfig;
/**
* 类名: MD5Utils</br>
* 描述: 数据签名MD5加密
*/
public class MD5Utils {
/**
* MD5签名
*
* @param paramSrc
* the source to be signed
* @return
* @throws Exception
*/
public static String sign(String paramSrc) {
String key = "";
try {
key = GetParamConfig.getParam("sign.key");
} catch (Exception e) {
e.printStackTrace();
}
String sign = md5(paramSrc + "&key=" + key);
System.out.println("MD5签名结果:" + sign);
return sign;
}
/**
* MD5验签
*
* @param source
* 签名内容
* @param sign
* 签名值
* @return
*/
public static boolean verify(String source, String signStr) {
String key = "";
try {
key = GetParamConfig.getParam("sign.key");
} catch (Exception e) {
e.printStackTrace();
}
String sign = md5(source + "&key=" + key);
System.out.println("自签结果:" + sign);
return signStr.equals(sign);
}
public final static String md5(String paramSrc) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = paramSrc.getBytes("utf-8");
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
-------------------------MD5----end-------------------
-------------------------requestutil --- start-----------
package com.util.sign;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.TreeMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;
import com.common.sign.SignConfig;
public class RequestUtils {
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
*/
public static String getParamSrc(TreeMap<String, String> paramsMap) {
StringBuffer paramstr = new StringBuffer();
for (String pkey : paramsMap.keySet()) {
String pvalue = paramsMap.get(pkey);
if (!StringUtils.isEmpty(pvalue)) {// 空值不传递,不签名
paramstr.append(pkey + "=" + pvalue + "&"); // 签名原串,不url编码
}
}
// 去掉最后一个&
String result = paramstr.substring(0, paramstr.length() - 1);
System.out.println("签名原串:" + result);
return result;
}
/**
* 分解解密后的字符串,保存为map
*/
public static HashMap<String, String> parseString(String responseData) {
HashMap<String, String> map = new HashMap<String, String>();
String[] s1 = responseData.split("&");
String[] s2 = new String[2];
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s1.length; i++) {
s2 = s1[i].split("=", 2);
map.put(s2[0], s2[1]);
if (!s2[0].equals("sign")) {
sb.append(s2[0] + "=" + s2[1] + "&");
}
}
String source = sb.substring(0, sb.length() - 1);
map.put("source", source);
return map;
}
/**
* 解析xml
*/
public static String getXmlElement(String responseData, String element) {
String result = null;
try {
Document dom = DocumentHelper.parseText(responseData);
Element root = dom.getRootElement();
result = root.element(element).getText();
} catch (DocumentException e1) {
e1.printStackTrace();
}
return result;
}
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), SignConfig.serverEncodeType));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
-------------------requestutil ---end -----------------------
--------------RSAUtil ---------------start --------------
package com.util.sign;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import com.common.sign.SignConfig;
import com.util.GetConfig;
/**
* 类名: RSAUtils</br>
* 描述: RSA数据签名和加解密
*/
public class RSAUtils {
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* RSA签名,目前服务端未支持
*
* @param paramSrc
* the source to be signed
* @return
*/
public static String sign(byte[] data) throws Exception {
byte[] digest = sha1(data);
String PRIVATE_KEY = "";
try {
PRIVATE_KEY = GetParamConfig.getParam("CLIENT_PRIVATE_KEY");
} catch (Exception e) {
e.printStackTrace();
}
byte[] encryptData = encryptByPrivateKey(digest, PRIVATE_KEY);
return Base64.encode(encryptData);
}
/**
* RSA验签
*
* @param source
* 签名内容
* @param sign
* 签名值
* @return
*/
public static boolean verify(String source, String sign) throws Exception {
byte[] digest = sha1(source.getBytes("GBK"));
String CLIENT_PUBLIC_KEY = "";
try {
CLIENT_PUBLIC_KEY = GetParamConfig.getParam("CLIENT_PUBLIC_KEY");
} catch (Exception e) {
e.printStackTrace();
}
byte[] encryptData = decryptByPublicKey(Base64.decode(sign), CLIENT_PUBLIC_KEY);
if (Arrays.equals(digest, encryptData)) {
return true;
} else {
return false;
}
}
/**
* 生成签名摘要
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
private static byte[] sha1(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = null;
md = MessageDigest.getInstance("SHA-1"); // 选择SHA-1,也可以选择MD5
byte[] digest = md.digest(data); // 返回的是byet[],要转化为String存储比较方便
return digest;
}
/**
* RSA加密
*
* @param paramstr
* @return
*/
public static String clientPubEncrypt(String paramstr) {
try {
String PUBLIC_KEY = "";
PUBLIC_KEY = GetParamConfig.getParam("CLIENT_PUBLIC_KEY");
byte[] cipherData = RSAUtils.encryptByPublicKey(paramstr.getBytes("UTF-8"), PUBLIC_KEY);
String result = Base64.encode(cipherData);
System.out.println("加密结果:" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA解密
*
* @param cipherData
* the data to be decrypt
* @return decryptByPrivateKey
*/
public static String clientPriDecrypt(String cipherData) {
try {
String PRIVATE_KEY = "";
PRIVATE_KEY = GetParamConfig.getParam("CLIENT_PRIVATE_KEY");
byte[] cipher = RSAUtils.decryptByPrivateKey(Base64.decode(cipherData), PRIVATE_KEY);
String result = new String(cipher,SignConfig.serverEncodeType);
System.out.println("解密结果:" + new String(result.getBytes("GBK"), "GBK"));
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA加密
*
* @param paramstr
* @return
*/
public static String serverPubEncrypt(String paramstr) {
try {
String PUBLIC_KEY = "";
PUBLIC_KEY = GetParamConfig.getParam("SERVER_PUBLIC_KEY");
byte[] cipherData = RSAUtils.encryptByPublicKey(paramstr.getBytes("UTF-8"), PUBLIC_KEY);
String result = Base64.encode(cipherData);
System.out.println("加密结果:" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA解密
*
* @param cipherData
* the data to be decrypt
* @return decryptByPrivateKey
*/
public static String serverPriDecrypt(String cipherData) {
try {
String PRIVATE_KEY = "";
PRIVATE_KEY = GetParamConfig.getParam("SERVER_PRIVATE_KEY");
byte[] cipher = RSAUtils.decryptByPrivateKey(Base64.decode(cipherData), PRIVATE_KEY);
String result = new String(cipher,SignConfig.serverEncodeType);
System.out.println("解密结果:" + new String(result.getBytes("GBK"), "GBK"));
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* <P>
* 私钥解密
* </p>
*
* @param data
* 要解密的数据
* @param privateKey
* 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(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 = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, 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[] decryptByPublicKey(byte[] data, String publicKey) throws Exception {
byte[] keyBytes = Base64.decode(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 = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, 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.decode(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.decode(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;
}
}
--------------RSAUitl ---------------end ---------------
------------------GetConfig -----------start ------------
package com.util;
/**
*
*
* @Package: com.subscription.util
* @ClassName: GetConfig
* @Description: 获取Conf.properties 里面的参数
*/
public class GetConfig {
public static String getParam(String key) {
return ConfigUtil.getProperty(key);
}
}
------------------GetConfig -----------start ------------
------------------ConfigUtil -----------start ------------
package com.util;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
*
*
* @Package: com.common.util
* @ClassName: ConfigUtil
* @Description: TODO
*/
@Component
public class ConfigUtil {
@Autowired
private Environment env;
private static Environment localEnv;
@PostConstruct
public void init() {
localEnv = this.env;
}
public static int getIntProperty(String key){
return Integer.parseInt(localEnv.getProperty(key)) ;
}
public static String getProperty(String key){
return localEnv.getProperty(key) ;
}
public static String getProperty(String key,String def){
if (StringUtils.isBlank(localEnv.getProperty(key))) {
return def ;
}
return localEnv.getProperty(key) ;
}
}
---------------------ConfigUtil -----------end ------------
-------------------------AbstractTest----start------------------------------
package com;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AbstractTest {
public MockMvc mvc;
public Map<String, Object> baseMap ;
@Autowired
WebApplicationContext wac ;
@Before
public void setup(){
/*
* MockMvcBuilders使用构建MockMvc对象.
*/
baseMap = new HashMap<>() ;
baseMap.put("param1",1);
baseMap.put("param2",1);
baseMap.put("param3","123123213213213213213");
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
}
-------------------------AbstractTest----end------------------------------
-------------------------SignControllerTest----start------------------------------
package com.test.controller;
import java.util.TreeMap;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.alibaba.fastjson.JSONObject;
import com.AbstractTest;
import com.util.StringUtil;
import com.util.sign.RSAUtils;
import com.util.sign.RequestUtils;
public class SignControllerTest extends AbstractTest{
private final static Logger log = LoggerFactory.getLogger(SignControllerTest.class);
@Test
public void testValidSign() throws Exception {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("activityId", "710183692382806016");
params.put("status", "0");
params.put("couponName", "优惠券名称0710001");
params.put("couponType", "1");
params.put("singleAmt", "10");
params.put("amtLimit", "500");
params.put("startTime", "");
params.put("endTime", "");
//mothod 2
//拼接签名原串
String paramSrc = RequestUtils.getParamSrc(params);
log.info("拼接签名原串(paramSrc):" + paramSrc);
// 原串转码,UTF-8转GBK
paramSrc = StringUtil.utf8ToUnicode(paramSrc);
//paramSrc = new String(paramSrc.getBytes(SignConfig.serverEncodeType), SignConfig.serverEncodeType);
log.info("转码后拼接签名串(paramSrc):" + paramSrc);
//md5签名
//String sign = MD5Utils.sign(paramSrc);
//RSA签名
String sign = RSAUtils.sign(paramSrc.getBytes("GBK"));
log.info("生成签名(sign):" + sign);
//rsa加密原串
String encryptSrc = paramSrc + "&sign=" + sign;//加密原串
//rsa密串
String cipherData = RSAUtils.serverPubEncrypt(encryptSrc);
log.info("生成加密数据(cipherData):" + cipherData);
JSONObject param = new JSONObject() ;
param.put("cipherData", cipherData);
String json = param.toString() ;
log.info("json格式参数:" + cipherData);
System.out.println("================================请求开始,入参:"+json);
RequestBuilder request = MockMvcRequestBuilders.post("/sign/validSign")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.header("SESSIONNO", "5qr24lk2k424jk24kj24k24k43")
.content(json) ;
MvcResult mvcResult = mvc.perform(request).andReturn() ;
int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();
Assert.assertTrue("错误,正确的返回值为200", status == 200);
Assert.assertFalse("错误,正确的返回值为200", status != 200);
System.out.println("返回结果:"+status);
System.out.println(content);
}
}
-------------------------SignControllerTest----end------------------------------
-------------------------SignController----start------------------------------
package com.controller;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.bean.Result;
import com.common.enums.ReturnCodeEnum;
import com.common.sign.RSA;
import com.common.sign.SignConfig;
import com.common.sign.SignCore;
import com.controller.vo.UserCouponVo;
import com.util.StringUtil;
import com.util.sign.RSAUtils;
import com.util.sign.RequestUtils;
@RestController
@RequestMapping("/sign")
public class SignController {
private final static Logger log = LoggerFactory.getLogger(SignController.class);
@RequestMapping(value="/modifyAct",method=RequestMethod.POST)
@ResponseBody
public Result modifyUser(HttpServletRequest request,HttpServletResponse response,@RequestBody UserCouponVo vo){
Map<String, String> params = new HashMap<String, String>();
params.put("activityId", vo.getActivityId());
params.put("status", vo.getStatus());
params.put("couponName", vo.getCouponName());
params.put("couponType", vo.getCouponType());
params.put("singleAmt", vo.getSingleAmt());
params.put("amtLimit", vo.getAmtLimit());
params.put("startTime", vo.getStartTime());
params.put("endTime", vo.getEndTime());
Map<String, String> sParaNew = SignCore.paraFilter(params);
//获取待签名字符串
String preSignStr = SignCore.createLinkString(sParaNew);
log.info("获取待签名字符串:" + preSignStr);
String signStr = "";
if(SignConfig.sign_type.equals("RSA")){
signStr = RSA.sign(preSignStr,SignConfig.private_key, SignConfig.input_charset);
}
if(!StringUtils.isEmpty(vo.getSign()) && !vo.getSign().equals(signStr)){
return new Result(ReturnCodeEnum.FAIL_SIGN.getCode(), ReturnCodeEnum.FAIL_SIGN.getDesc());
}
return new Result(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getDesc());
}
@RequestMapping(value = "/validSign", method = RequestMethod.POST)
@ResponseBody
public Result validSign(HttpServletRequest request,HttpServletResponse response,@RequestBody UserCouponVo vo){
if(StringUtils.isEmpty(vo.getCipherData())){
return new Result(ReturnCodeEnum.SIGN_NULL.getCode(), ReturnCodeEnum.SIGN_NULL.getDesc());
}
log.info("请求参数加密数据串:" + JSON.toJSONString(vo));
//数据解密
String responseData = RSAUtils.serverPriDecrypt(vo.getCipherData());
//封装数据
HashMap<String, String> map = RequestUtils.parseString(responseData);
log.info("验签数据串:source ={}" ,map.get("source"));
try {
//rsa验签
if (RSAUtils.verify(map.get("source"), map.get("sign"))) {
//MD5验签
//if (MD5Utils.verify(map.get("source"), map.get("sign"))) {
log.info("rsa验签,验签结果:通过");
} else {
log.info("rsa验签,验签结果:未通过");
}
} catch (Exception e) {
log.error("验签异常", e);
}
log.info("解密后的请求参数数据:map={}",JSON.toJSONString(map));
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
Map<String, String> paramMap = new HashMap<>();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
paramMap.put(entry.getKey(), StringUtil.unicodeToUtf8(entry.getValue()));
}
log.info("解密并转码后的数据:map={}",JSON.toJSONString(paramMap));
return new Result(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getDesc(),paramMap);
}
}
-------------------------SignController---end------------------------------
-------------------------base64----start------------------------------
public final class Base64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData
* Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets);
}
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
if (fDebug) {
System.out.println("val2 = " + val2);
System.out.println("k4 = " + (k << 4));
System.out.println("vak = " + (val2 | (k << 4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded
* string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
// if (len % FOURBYTE != 0) {
// return null;// should be divisible by four
// }
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) {
return null;
} // if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0) // last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0) // last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data
* the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
-------------------------base64----end------------------------------
-------------------------MD5----start------------------------------
package com.util.sign;
import java.security.MessageDigest;
import com.util.GetParamConfig;
/**
* 类名: MD5Utils</br>
* 描述: 数据签名MD5加密
*/
public class MD5Utils {
/**
* MD5签名
*
* @param paramSrc
* the source to be signed
* @return
* @throws Exception
*/
public static String sign(String paramSrc) {
String key = "";
try {
key = GetParamConfig.getParam("sign.key");
} catch (Exception e) {
e.printStackTrace();
}
String sign = md5(paramSrc + "&key=" + key);
System.out.println("MD5签名结果:" + sign);
return sign;
}
/**
* MD5验签
*
* @param source
* 签名内容
* @param sign
* 签名值
* @return
*/
public static boolean verify(String source, String signStr) {
String key = "";
try {
key = GetParamConfig.getParam("sign.key");
} catch (Exception e) {
e.printStackTrace();
}
String sign = md5(source + "&key=" + key);
System.out.println("自签结果:" + sign);
return signStr.equals(sign);
}
public final static String md5(String paramSrc) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = paramSrc.getBytes("utf-8");
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str).toLowerCase();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
-------------------------MD5----end-------------------
-------------------------requestutil --- start-----------
package com.util.sign;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.TreeMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;
import com.common.sign.SignConfig;
public class RequestUtils {
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
*/
public static String getParamSrc(TreeMap<String, String> paramsMap) {
StringBuffer paramstr = new StringBuffer();
for (String pkey : paramsMap.keySet()) {
String pvalue = paramsMap.get(pkey);
if (!StringUtils.isEmpty(pvalue)) {// 空值不传递,不签名
paramstr.append(pkey + "=" + pvalue + "&"); // 签名原串,不url编码
}
}
// 去掉最后一个&
String result = paramstr.substring(0, paramstr.length() - 1);
System.out.println("签名原串:" + result);
return result;
}
/**
* 分解解密后的字符串,保存为map
*/
public static HashMap<String, String> parseString(String responseData) {
HashMap<String, String> map = new HashMap<String, String>();
String[] s1 = responseData.split("&");
String[] s2 = new String[2];
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s1.length; i++) {
s2 = s1[i].split("=", 2);
map.put(s2[0], s2[1]);
if (!s2[0].equals("sign")) {
sb.append(s2[0] + "=" + s2[1] + "&");
}
}
String source = sb.substring(0, sb.length() - 1);
map.put("source", source);
return map;
}
/**
* 解析xml
*/
public static String getXmlElement(String responseData, String element) {
String result = null;
try {
Document dom = DocumentHelper.parseText(responseData);
Element root = dom.getRootElement();
result = root.element(element).getText();
} catch (DocumentException e1) {
e1.printStackTrace();
}
return result;
}
public static String doPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), SignConfig.serverEncodeType));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
-------------------requestutil ---end -----------------------
--------------RSAUtil ---------------start --------------
package com.util.sign;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.Cipher;
import com.common.sign.SignConfig;
import com.util.GetConfig;
/**
* 类名: RSAUtils</br>
* 描述: RSA数据签名和加解密
*/
public class RSAUtils {
/**
* 加密算法RSA
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* RSA签名,目前服务端未支持
*
* @param paramSrc
* the source to be signed
* @return
*/
public static String sign(byte[] data) throws Exception {
byte[] digest = sha1(data);
String PRIVATE_KEY = "";
try {
PRIVATE_KEY = GetParamConfig.getParam("CLIENT_PRIVATE_KEY");
} catch (Exception e) {
e.printStackTrace();
}
byte[] encryptData = encryptByPrivateKey(digest, PRIVATE_KEY);
return Base64.encode(encryptData);
}
/**
* RSA验签
*
* @param source
* 签名内容
* @param sign
* 签名值
* @return
*/
public static boolean verify(String source, String sign) throws Exception {
byte[] digest = sha1(source.getBytes("GBK"));
String CLIENT_PUBLIC_KEY = "";
try {
CLIENT_PUBLIC_KEY = GetParamConfig.getParam("CLIENT_PUBLIC_KEY");
} catch (Exception e) {
e.printStackTrace();
}
byte[] encryptData = decryptByPublicKey(Base64.decode(sign), CLIENT_PUBLIC_KEY);
if (Arrays.equals(digest, encryptData)) {
return true;
} else {
return false;
}
}
/**
* 生成签名摘要
*
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
private static byte[] sha1(byte[] data) throws NoSuchAlgorithmException {
MessageDigest md = null;
md = MessageDigest.getInstance("SHA-1"); // 选择SHA-1,也可以选择MD5
byte[] digest = md.digest(data); // 返回的是byet[],要转化为String存储比较方便
return digest;
}
/**
* RSA加密
*
* @param paramstr
* @return
*/
public static String clientPubEncrypt(String paramstr) {
try {
String PUBLIC_KEY = "";
PUBLIC_KEY = GetParamConfig.getParam("CLIENT_PUBLIC_KEY");
byte[] cipherData = RSAUtils.encryptByPublicKey(paramstr.getBytes("UTF-8"), PUBLIC_KEY);
String result = Base64.encode(cipherData);
System.out.println("加密结果:" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA解密
*
* @param cipherData
* the data to be decrypt
* @return decryptByPrivateKey
*/
public static String clientPriDecrypt(String cipherData) {
try {
String PRIVATE_KEY = "";
PRIVATE_KEY = GetParamConfig.getParam("CLIENT_PRIVATE_KEY");
byte[] cipher = RSAUtils.decryptByPrivateKey(Base64.decode(cipherData), PRIVATE_KEY);
String result = new String(cipher,SignConfig.serverEncodeType);
System.out.println("解密结果:" + new String(result.getBytes("GBK"), "GBK"));
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA加密
*
* @param paramstr
* @return
*/
public static String serverPubEncrypt(String paramstr) {
try {
String PUBLIC_KEY = "";
PUBLIC_KEY = GetParamConfig.getParam("SERVER_PUBLIC_KEY");
byte[] cipherData = RSAUtils.encryptByPublicKey(paramstr.getBytes("UTF-8"), PUBLIC_KEY);
String result = Base64.encode(cipherData);
System.out.println("加密结果:" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA解密
*
* @param cipherData
* the data to be decrypt
* @return decryptByPrivateKey
*/
public static String serverPriDecrypt(String cipherData) {
try {
String PRIVATE_KEY = "";
PRIVATE_KEY = GetParamConfig.getParam("SERVER_PRIVATE_KEY");
byte[] cipher = RSAUtils.decryptByPrivateKey(Base64.decode(cipherData), PRIVATE_KEY);
String result = new String(cipher,SignConfig.serverEncodeType);
System.out.println("解密结果:" + new String(result.getBytes("GBK"), "GBK"));
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* <P>
* 私钥解密
* </p>
*
* @param data
* 要解密的数据
* @param privateKey
* 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.decode(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 = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, 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[] decryptByPublicKey(byte[] data, String publicKey) throws Exception {
byte[] keyBytes = Base64.decode(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 = data.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(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, 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.decode(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.decode(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;
}
}
--------------RSAUitl ---------------end ---------------
------------------GetConfig -----------start ------------
package com.util;
/**
*
*
* @Package: com.subscription.util
* @ClassName: GetConfig
* @Description: 获取Conf.properties 里面的参数
*/
public class GetConfig {
public static String getParam(String key) {
return ConfigUtil.getProperty(key);
}
}
------------------GetConfig -----------start ------------
------------------ConfigUtil -----------start ------------
package com.util;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
*
*
* @Package: com.common.util
* @ClassName: ConfigUtil
* @Description: TODO
*/
@Component
public class ConfigUtil {
@Autowired
private Environment env;
private static Environment localEnv;
@PostConstruct
public void init() {
localEnv = this.env;
}
public static int getIntProperty(String key){
return Integer.parseInt(localEnv.getProperty(key)) ;
}
public static String getProperty(String key){
return localEnv.getProperty(key) ;
}
public static String getProperty(String key,String def){
if (StringUtils.isBlank(localEnv.getProperty(key))) {
return def ;
}
return localEnv.getProperty(key) ;
}
}
---------------------ConfigUtil -----------end ------------
相关文章推荐
- Java中使用RSA对请求和接收数据进行签名校验
- Java JUnit 调用Excel表中数据 参数化测试 JUnit4
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- [置顶] 数据传输加密——非对称加密算法RSA+对称算法AES(适用于java,android和Web)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- 一组PKCS#11 RSA签名测试数据
- 数据传输加密:非对称加密算法RSA+对称算法AES(适用于java,android和Web)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- java实现RSA非对称加密算法 对数据进行加密【附代码】
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Java 实现MD5消息摘要和RSA数字签名:
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Android网络传输中必用的两个加密算法:MD5 和 RSA (附java完成测试代码)
- Java Map的再深入研究(百万级数据测试)
- Java Map的再深入研究(百万级数据测试)