工作中经常有和第三方机构联调接口的事情,顾将用到过的做以记录。
在和第三方联调时,主要步骤为:网络、加解密/签名验签、接口数据等,其中接口数据没啥好说的。
在联调前就需要先将两边的网络连通,一般公司的生产环境都加了防火墙,测试环境有的是有防火墙,有的则没有防火墙,这个需要和第三方人员沟通,如果有防火墙的就需要将我们的出口ip或域名发送给第三方做配置,配置了之后网络一般都是通的。
加解密与签名验签:
一般第三方公司都会有加解密或签名验签的,毕竟为了数据安全。一般就是三种:
一、有加密,无签名
这种方式秘钥是最主要的,在发送请求前,秘钥就需要人为的给第三方。
我司请求第三方:
按照接口文档格式组装数据,利用秘钥进行签名
将结果发送给第三方
第三方请求我司:
请求的时候反过来
此处附上aes加解密代码
public static final String CHARSET = "UTF-8";
public static final String AES_ALGORITHM = "AES";
/**
* @param content 加密前数据
* @return
* @description: AES加密算法入口
*/
public static String encrypt4Aes(String content, String secretKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
byte[] src = content.getBytes(encoding);
//加密
byte[] bytOut = encryptMode(src, secretKey);
return base64encode(bytOut);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("加密时string转byte出错:", e);
}
}
/**
* @param src 加密前数据字节
* @return
* @description: AES加密实现
*/
public static byte[] encryptMode(byte[] src, String secretKey) {
try {
Cipher cip = Cipher.getInstance(AES_ALGORITHM);
cip.init(Cipher.ENCRYPT_MODE, getSecretKey(secretKey));
return cip.doFinal(src);
} catch (Exception e3) {
throw new RuntimeException("加密出现异常:", e3);
}
}
// 将 s 进行 BASE64 编码
public static String base64encode(byte[] src) {
if (src == null) return null;
return (new sun.misc.BASE64Encoder()).encode(src);
}
public static SecretKey getSecretKey(String secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
byte[] keybyte = getKeyByStr(secretKey);
// 初始化算法,设置成“SHA1PRNG”是为了防止在linux环境下随机生成算法
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keybyte);
KeyGenerator keygen = KeyGenerator.getInstance(AES_ALGORITHM);
keygen.init(secureRandom);
return keygen.generateKey();
}
public static byte[] getKeyByStr(String str) {
byte[] bRet = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
Integer itg = new Integer(16 * getChrInt(str.charAt(2 * i)) + getChrInt(str.charAt(2 * i + 1)));
bRet[i] = itg.byteValue();
}
return bRet;
}
public static int getChrInt(char chr) {
int iRet = 0;
if (chr == "0".charAt(0)) iRet = 0;
if (chr == "1".charAt(0)) iRet = 1;
if (chr == "2".charAt(0)) iRet = 2;
if (chr == "3".charAt(0)) iRet = 3;
if (chr == "4".charAt(0)) iRet = 4;
if (chr == "5".charAt(0)) iRet = 5;
if (chr == "6".charAt(0)) iRet = 6;
if (chr == "7".charAt(0)) iRet = 7;
if (chr == "8".charAt(0)) iRet = 8;
if (chr == "9".charAt(0)) iRet = 9;
if (chr == "A".charAt(0)) iRet = 10;
if (chr == "B".charAt(0)) iRet = 11;
if (chr == "C".charAt(0)) iRet = 12;
if (chr == "D".charAt(0)) iRet = 13;
if (chr == "E".charAt(0)) iRet = 14;
if (chr == "F".charAt(0)) iRet = 15;
return iRet;
}
/**
* AES算法解密入口
*/
public static String decrypt4Aes2Str(String contentbase64, String secretKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
String Result = null;
byte[] dst = decrypt4Aes(contentbase64, secretKey);
if (null != dst) {
try {
Result = new String(dst, encoding);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("解密时byte转string出现异常:", e);
}
}
return Result;
}
public static byte[] decrypt4Aes(String contentbase64, String secretKey) {
byte[] src = base64decode(contentbase64);
// 解密
return decryptMode(src, secretKey);
}
public static byte[] decryptMode(byte[] src, String secretKey) {
try {
Cipher cip = Cipher.getInstance(AES_ALGORITHM);
cip.init(Cipher.DECRYPT_MODE, getSecretKey(secretKey));
return cip.doFinal(src);
} catch (Exception e) {
throw new RuntimeException("解密时出现异常:", e);
}
}
// 将 BASE64 编码的字符串 s 进行解码
public static byte[] base64decode(String s) {
if (s == null)
return null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(s);
return b;
} catch (Exception e) {
throw new RuntimeException("base64编解码出现异常:", e);
}
}
二、无加密,只有签名
我司请求第三方:
按照接口文档数据格式进行组装数据(如aa=*&bb=*&....格式),组装好后,这部分就是明文
用我司的私钥对明文进行签名
将签名得到的数据再与明文拼接(例如结果为:aa=*&bb=*&....&sign=签名结果字符串,此处sign表示对方约定存放签名的字段名)
将最终结果传送给第三方
第三方请求我司:
我司将接收到的数据根据接口文档的数据组装格式进行解析,解析后的数据为明文&签名
能够获取到明文字符串和签名字符串,然后利用第三方的公钥进行延签
验签返回值为Boolean类型,即成功或失败,如果成功就继续操作,失败则证明数据再传输途中发生了变动
三、有加密,有签名
我司请求第三方:
将需要加密的数据利用秘钥加密,再用我司私钥将秘钥加密,再按照规定格式组装数据
将上面的数据利用我司私钥签名
将签名得到的数据再与明文拼接(例如结果为:aa=*&bb=*&....&sign=签名结果字符串,此处sign表示对方约定存放签名的字段名)
将最终结果传送给第三方
第三方请求我司:
我司将接收到的数据根据接口文档的数据组装格式进行解析,解析后的数据为明文&签名
能够获取到明文字符串和签名字符串,然后利用第三方的公钥进行延签
验签返回值为Boolean类型,即成功或失败,如果成功就继续操作,失败则证明数据再传输途中发生了变动
此时明文中还有加密的数据,再利用第三方公钥解密得到数据加密的秘钥,然后再用此秘钥对加密数据解密即得到最终明文
此处给出第三种的例子:
这种接口文档中,由于客户信息四要素是不能公开的,而用签名时,发送的数据是‘明文&签名’,这种形式中的明文就将客户信息暴露了,所以要对客户信息进行加密,此时选择的AES加密,而用AES加密时,此处采用的不是提前将AES秘钥发送给第三方做配置,而是实时传输,所以AES秘钥也不能暴露,顾利用RSA对AES秘钥加密,采用的是RSA私钥加密,最终的报文中的明文处content是json数据经过AES加密后的结果,aesKey是AES秘钥经过RSA私钥加密后的结果。
第三方在接收到数据后,将明文与签名拆开,利用我们的公钥对明文和密文做验签,验签通过后,再拆出aesKey密文,利用公钥做解密,得到AES秘钥明文,然后对content做AES解密,得到最终的用户数据。至此,请求的报文的所有明文都解析出来了。
附上RSA加解密与签名验签的代码:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* @Author:wangjinhui
* @Created time: 2018/9/5
* @Desc: RSA加解密与签名验签
* 1、公钥加密,则用私钥解密
* 2、私钥加密,则用公钥解密
* 3、公钥签名,私钥验签
* 4、加密类型:非对称加密
* 优缺点:
* 优点:更安全,秘钥越长,越难破解
* 缺点:加密速度慢
*/
public class RSAUtils {
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
public static final String RSA_ALGORITHM_SIGN = "SHA256WithRSA";
/**
* 初始化RSA算法密钥对
*
* @param keySize RSA1024已经不安全了,建议2048
* @return 经过Base64编码后的公私钥Map, 键名分别为publicKey和privateKey
*/
private static Map<String, String> createKeys(int keySize) {
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
}
//初始化KeyPairGenerator对象,密钥长度
kpg.initialize(keySize);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
Map<String, String> keyPairMap = new HashMap<String, String>();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
* 得到公钥
* @param publicKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过X509编码的Key指令获得公钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
/**
* 得到私钥
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
/**
* 公钥加密
* @param data
* @param publicKey
* @return
*/
public static String publicEncrypt(String data, RSAPublicKey publicKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(encoding), publicKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥解密
* @param data
* @param privateKey
* @return
*/
public static String privateDecrypt(String data, RSAPrivateKey privateKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), encoding);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥加密
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(encoding), privateKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 公钥解密
* @param data
* @param publicKey
* @return
*/
public static String publicDecrypt(String data, RSAPublicKey publicKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), encoding);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥签名
* @param data 需要签名的数据
* @param privateKey 私钥
* @return
*/
public static String sign(String data, RSAPrivateKey privateKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
//sign
Signature signature = Signature.getInstance(RSA_ALGORITHM_SIGN);
signature.initSign(privateKey);
signature.update(data.getBytes(encoding));
return Base64.encodeBase64URLSafeString(signature.sign());
} catch (Exception e) {
throw new RuntimeException("签名字符串[" + data + "]时遇到异常", e);
}
}
/**
* 公钥验签
* @param data 需要验签的原始数据
* @param sign 签名
* @param publicKey 公钥
* @return
*/
public static boolean verify(String data, String sign, RSAPublicKey publicKey, String encoding) {
if (StringUtils.isEmpty(encoding)) {
encoding = CHARSET;
}
try {
Signature signature = Signature.getInstance(RSA_ALGORITHM_SIGN);
signature.initVerify(publicKey);
signature.update(data.getBytes(encoding));
return signature.verify(Base64.decodeBase64(sign));
} catch (Exception e) {
throw new RuntimeException("验签字符串[" + data + "]时遇到异常", e);
}
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}