建行银企直连
客户端加密方式:服务方使用 DES算法对密钥加密,使用DES/ECB/PKCS5Padding填充;
DES密钥约定为:企业客户号+交换当日日期(YYMMDD 6 位)
/**
* 初始化DES密钥(DES密钥约定为:企业客户号 + 交换当日日期-YYMMDD)
* @param customerNo 取后 10 位,不足 10 位的,前面补 0
* @return
* @throws Exception
*/
public static byte[] initDesKey(String customerNo) throws Exception{
if(customerNo.length() >= 10){
customerNo = customerNo.substring(customerNo.length() - 10);
}else{
customerNo = String.format("%0" + (10 - customerNo.length()) + "d", 0) + customerNo;
}
String sKey = customerNo + new SimpleDateFormat("yyMMdd").format(new Date());
return asc2bin(sKey);
}
数据签名
/**
* 数字签名
* @param data 待签名数据
* @return 签名
*/
public static String sign(String data,String rsaKey) throws Exception{
byte[] keyBytes = Base64.decodeBase64(rsaKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(key);
signature.update(data.getBytes("UTF-8"));
return new String(Base64.encodeBase64(signature.sign()),"UTF-8");
}
报文加密
/**
* 报文加密 DESede (3DES)
* @throws Exception
*/
public static String encryptWithDESede(String data,String desKey) throws Exception {
byte[] sourceBytes = data.getBytes("UTF-8");
byte[] keyBytes = Base64.decodeBase64(desKey);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_XML);
cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM_XML));
byte[] decrypted = cipher.doFinal(sourceBytes);
return Base64.encodeBase64String(decrypted);
}
报文解密
/**
* 报文解密 DESede (3DES)
* @param encryptStr
* @param key
* @return
* @throws Exception
*/
public static String decryptWithDESede(byte[] data, String key) throws Exception {
byte[] keyBytes = Base64.decodeBase64(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_XML);
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(keyBytes, KEY_ALGORITHM_XML));
byte[] decoded = cipher.doFinal(data);
return new String(decoded, "UTF-8");
}
返回验签
/**
* 验签
* @param sign
* @param srcData
* @param public_Key
* @return
* @throws Exception
*/
public static boolean verify(String sign, String srcData ,String public_Key) throws Exception {
byte[] keyBytes = Base64.decodeBase64(public_Key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(key);
signature.update(srcData.getBytes("UTF-8"));
return signature.verify(Base64.decodeBase64(sign.getBytes("UTF-8")));
}