一
最近对接了很多第三方支付产品,由于涉及到敏感信息及金钱等非常重要的数据,数据传输安全就显得尤为重要。那么实际是怎样处理的呢?
一般的数据传输流程大概如下:
1.调用支付接口时,将数据信息+商户私钥生成签名,将数据和签名一同发给支付机构
2.支付机构方留有商户的公钥,收到数据时,用商户公钥+数据信息+签名来验证数据的身份和一致性
3.异步通知到商户时,支付机构将数据信息和签名信息一同付给商户服务器
4.商户方留有支付机构的公钥,收到数据时,用支付机构公钥+数据信息+签名来验证数据的身份和一致性
二
下面自己写了一个demo,希望能对各位同学有所帮助:
1.工具类
package com.cyq.util;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
/**
* @author cyq
*/
public class HmacDigestUtil {
static char[] hexDigits ={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
private static final String DEFAULT_ALGO = "HmacSHA1";
private static final String ENCODING = "UTF-8";
public static String toHex(byte[] data) {
// 把密文转换成十六进制的字符串形式
int j = data.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = data[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
public static byte[] hmacEncrypt(String encryptText, String encryptKey, String algorithm) throws Exception {
if (algorithm == null || "".equals(algorithm)) {
algorithm = DEFAULT_ALGO;
}
byte[] data = encryptKey.getBytes(ENCODING);
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKey secretKey = new SecretKeySpec(data, algorithm);
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(algorithm);
//用给定密钥初始化 Mac 对象
mac.init(secretKey);
byte[] text = encryptText.getBytes(ENCODING);
//完成 Mac 操作
return mac.doFinal(text);
}
public static String hmacEncryptString(String encryptText, String encryptKey, String algorithm) throws Exception {
return toHex(hmacEncrypt(encryptText, encryptKey, algorithm));
}
public final static byte[] md5(String s) {
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
return md;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public final static String md5String(String s) {
return toHex(md5(s));
}
}
2.数据传输类(含测试)
package com.cyq.secusign;
import com.cyq.util.HmacDigestUtil;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
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;
/**
* @author cyq
*/
public class SecureDataTrans {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
private static final String ALGO = "HmacSHA256";
private static String APPKEY = "app:326215423";
public static void main(String[] args) throws Exception {
// 获取密钥对
genPairs();
String publicKey = keyMap.get(0);
String privateKey = keyMap.get(1);
System.out.println("publicKey:" + keyMap.get(0));
System.out.println("privateKey:" + keyMap.get(1));
/////////////发送数据
// 需要发送的数据
Map<String, String> data = new HashMap<>();
data.put("name", "chinoukin");
data.put("age", "22");
data.put("address", "Beijing haidian");
System.out.println(data);
// 发送的数据里加上签名
String signature = sign(data, publicKey);
System.out.println("signature:" + signature);
data.put("signature", signature);
/////////////接收数据
// 验证签名
if (verify(data, privateKey)) {
System.out.println("验签通过!");
System.out.println(data);
}
}
public static void genPairs() {
try {
// 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表示私钥
} catch (Throwable e) {
}
}
/**
* 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;
}
/**
* 签名数据
*
* @param data
* @param publicKey
* @return
* @throws Exception
*/
public static String sign(Map<String, String> data, String publicKey) throws Exception {
// 对数据进行信息摘要
String dataStr = "";
for (String key : data.keySet()) {
dataStr += key + "=" + data.get(key) + "&";
}
// 此处用Md5做信息摘要,也可以是HMAC
//String digest = HmacDigestUtil.md5String(dataStr);
String digest = HmacDigestUtil.hmacEncryptString(dataStr, APPKEY, ALGO);
System.out.println("digest:" + digest);
return encrypt(digest, publicKey);
}
/**
* 验证签名
*
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static boolean verify(Map<String, String> data, String privateKey) throws Exception {
String signature = data.get("signature");
String sourceDigest = decrypt(signature, privateKey);
String dataStr = "";
for (String key : data.keySet()) {
if ("signature".endsWith(key)) {
continue;
}
dataStr += key + "=" + data.get(key) + "&";
}
// 此处用Md5做信息摘要,也可以是HMAC
//String digest = HmacDigestUtil.md5String(dataStr);
// return true;
//}
if (HmacDigestUtil.hmacEncryptString(dataStr, APPKEY, ALGO).equals(sourceDigest)) {
return true;
}
return false;
}
}
3.运行结果
publicKey:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBhdrSKEciXgo5PA4A9VeBiRMETrfYMdvzGnu7m+eeKc/GA9ggQVQMIPWl5bsC1AcN0qqV3CxKhIAqosmLscxpb4MbrfBC0mCzqvCm4I+b4NCOzBox1GC8suAm8I89crX02MflJ9X6Tdfa46K+Wjhi1Tl3O0C+EvsUig9YkEPIKwIDAQAB
privateKey:MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIGF2tIoRyJeCjk8DgD1V4GJEwROt9gx2/Mae7ub554pz8YD2CBBVAwg9aXluwLUBw3SqpXcLEqEgCqiyYuxzGlvgxut8ELSYLOq8Kbgj5vg0I7MGjHUYLyy4Cbwjz1ytfTYx+Un1fpN19rjor5aOGLVOXc7QL4S+xSKD1iQQ8grAgMBAAECgYBT71BcvGlMpjBt4rMYf+VTNmcydWjCG51zrwfcDi5M2r+gjME0NeGncnx+I5/LN2fS12BgeSvipncAKjn94xyZjwLu85Ar1tklvpH3C9TXCxBdKiNPNwtg0Zsg8PdLobdhv8tZNdQwVawhVNyuV4QlfrIWvpMbaAFDFDRmEAObEQJBANrBLa27E4q+oX7Nl6GNxl/b5gQSQJv6xolA/yI9d6bPKxEclpxDt1CNJW8NFV/PlPYu9ziLnapYiBMw1m8z9tUCQQCXk1jh6tqI+vor5ciNsc3J62lLMVhRQNfilzINdw6R4k6HXsWik7UVi3oyQTpIYcH0jPgB+RiT9WmBo1BZZkL/AkAdIFeKqDwD3zn1fj5QPmZJYSgRJrT/j7ZblBHkZzbFORRM5PeQuttvmDuBu8Y6yZLV7I7yMnS9t6f2liwXBl45AkEAkMFLVRXw9niZimq8CXYQzhFgUUsiyRZgFinGx004QOIblPRRUl41xgmZ/XyFqLKThHVMNLYrXsI0rHXHOlmLCQJADpXtrVSxvO2A0leMbirAYGIH1atKC9fJYXqHHSE7THbB+MlBuv+ma6TEBXTV01N+PxtiWiYh7X1uSZESC3kQLQ==
{address=Beijing haidian, name=chinoukin, age=22}
digest:6C9674BBC050314363BB9DD37CE80DC6970218F43F9F15F886A4A0B31E3BE523
signature:Pqx5lEfGeOEN4wKUUbvpI9P2Vy7ddc7MQLLzOIs2l+26EZglkESCVMsC5ApS34Qs7cMWu5MB3+rb0vTOpM9INsdvdohSOImbgWIAhjrLmENayIsI7fcyhoOCTA/BMlAWn7GJFWwl0sXgR/Lp5D5na4kgFP2TnRzqAXsJGtFdzrE=
验签通过!
{address=Beijing haidian, signature=Pqx5lEfGeOEN4wKUUbvpI9P2Vy7ddc7MQLLzOIs2l+26EZglkESCVMsC5ApS34Qs7cMWu5MB3+rb0vTOpM9INsdvdohSOImbgWIAhjrLmENayIsI7fcyhoOCTA/BMlAWn7GJFWwl0sXgR/Lp5D5na4kgFP2TnRzqAXsJGtFdzrE=, name=chinoukin, age=22}
来源:https://blog.csdn.net/chinoukin/article/details/100934995