对接API接口的时候往往为了安全考虑,需要实现数据签名和验签,最常用的就是使用公私钥对进行签名验签,主要流程为:
1、生成公私钥对
2、使用私钥进行签名
3、使用公钥验证签名
这么最的主要目的是为了保证请求来源的合法性,参数的正确性(不被篡改)
废话不多说,直接撸出工具类,本次工具类一共3个。Rsa.java、Base64.java、BaseHelper.java。生成签名的时候将需要传递的参数bean通过BaseHelper.sortParamAll(bean)转成K=V&K1=V1......的形式,然后调用Rsa.sign()方法即可生成签名。
验签的时候获取到传递过来的参数json串(jsonParams),同样将业务参数通过BaseHelper.sortCheckParam(jsonParams)转成K=V&K1=V1......的形式(剔除sign参数),然后调用Rsa.doCheck()方法验证签名是否通过。
传递参数示例:
{
"name": "zhangsan",
"age": "34",
"amont": "100.00",
"sign": "bpy8NrCnRq8lK9wVWI0EHNJVUgEpJFWlwOIIvMOUYfflQsvRzw8gCFNLpT/0pTOHeHwB/Cn8tMmXCzv9fnm8cUXlAAofsRYOneVseGt+ArgtsXGitjACA0L3Krbn2SsG+xEL/VbMGW2UwyLHx8FNz88ZzbORSKaERPC7tL3MWpQ=",
"time": "20170831103259"
}
package cn.test;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA工具类
*
*/
public class Rsa {
public static final String SIGN_ALGORITHMS = "MD5WithRSA";
/**
* @param content:签名的参数内容
* @param privateKey:私钥
* @return
*/
public static String sign(String content, String privateKey) {
String charset = "utf-8";
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param content:验证参数的内容
* @param sign:签名
* @param publicKey:公钥
* @return
*/
public static boolean doCheck(String content, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update(content.getBytes("utf-8"));
boolean bverify = signature.verify(Base64.decode(sign));
return bverify;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package cn.test;
/**
* Base64 工具类
*
*/
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;
}
}
package cn.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* 工具类
*/
public class BaseHelper {
private final static Logger log = Logger.getLogger(BaseHelper.class);
public static final String PARAM_EQUAL = "=";
public static final String PARAM_AND = "&";
public static String toJSONString(Object obj) {
JSONObject json = new JSONObject();
try {
Map<String, String> map = bean2Parameters(obj);
for (Map.Entry<String, String> entry : map.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 对Object进行List<NameValuePair>转换后按key进行升序排序,以key=value&...形式返回
*
* @param list
* @return
*/
public static String sortParam(Object order) {
Map<String, String> map = bean2Parameters(order);
return sortParam(map);
}
public static String sortParamAll(Object order) {
Map<String, String> map = bean2Parameters(order);
return sortCheckParam(map);
}
/**
* 对Object进行List<NameValuePair>转换后按key进行升序排序,以key=value&...形式返回
*
* @param list
* @return
*/
public static String sortCheckParam(Map<String, String> order) {
if (order == null) {
return null;
}
Map<String, String> parameters = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String obj1, String obj2) {
return obj1.compareToIgnoreCase(obj2);
}
});
parameters.putAll(order);
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (null != entry.getValue() && !"".equals(entry.getValue()) && !entry.getKey().equals("sign")) {
sb.append(entry.getKey());
sb.append(PARAM_EQUAL);
sb.append(entry.getValue());
sb.append(PARAM_AND);
}
}
String params = sb.toString();
if (sb.toString().endsWith(PARAM_AND)) {
params = sb.substring(0, sb.length() - 1);
}
log.info("待签名串:" + params);
return params;
}
/**
* 将bean转换成键值对列表
*
* @param bean
* @return
*/
public static Map<String, String> bean2Parameters(Object bean) {
if (bean == null) {
return null;
}
Map<String, String> parameters = new HashMap<String, String>();
if (null != parameters) {
// 取得bean所有public 方法
Method[] Methods = bean.getClass().getMethods();
for (Method method : Methods) {
if (method != null && method.getName().startsWith("get") && !method.getName().startsWith("getClass")) {
// 得到属性的类名
String value = "";
// 得到属性值
try {
String className = method.getReturnType().getSimpleName();
if (className.equalsIgnoreCase("int")) {
int val = 0;
try {
val = (Integer) method.invoke(bean);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
value = String.valueOf(val);
} else if (className.equalsIgnoreCase("String")) {
try {
value = (String) method.invoke(bean);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
if (value != null && value != "") {
// 添加参数
// 将方法名称转化为id,去除get,将方法首字母改为小写
String param = method.getName().replaceFirst("get", "");
if (param.length() > 0) {
String first = String.valueOf(param.charAt(0)).toLowerCase();
param = first + param.substring(1);
}
parameters.put(param, value);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
return parameters;
}
/**
* 对对Object转换后, 以key=value&...形式返回按key进行升序排序,以key=value&...形式返回
*
* @param order
* @return
*/
public static String sortParam(Map<String, String> order) {
if (null == order) {
return null;
}
Map<String, String> parameters = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String obj1, String obj2) {
return obj1.compareToIgnoreCase(obj2);
}
});
parameters.putAll(order);
if (null != parameters) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (null != entry.getValue() && !"".equals(entry.getValue()) && !entry.getKey().equals("id_type")
&& !entry.getKey().equals("id_no") && !entry.getKey().equals("acct_name")
&& !entry.getKey().equals("flag_modify") && !entry.getKey().equals("user_id")
&& !entry.getKey().equals("no_agree") && !entry.getKey().equals("card_no")
&& !entry.getKey().equals("test_mode")) {
sb.append(entry.getKey());
sb.append(PARAM_EQUAL);
sb.append(entry.getValue());
sb.append(PARAM_AND);
}
}
String params = sb.toString();
if (sb.toString().endsWith(PARAM_AND)) {
params = sb.substring(0, sb.length() - 1);
}
log.info("待签名串:" + params);
return params;
}
return null;
}
}