原理:
1 客户端使用一串字符串,然后使用私钥加密数据。
2 服务端使用相同的字符串,使用公钥解密还原数据。
/**
* 获取电子保单示例程序
* 注意:本示例仅供参考演示,生产代码请合作伙伴另行编写
* @author HXS 2012-12-23
*
*/
public class BytestreamRealTimeTransDemo {
/**
* 为简洁起见,配置信息作为静态变量,如有调整,可进行修改
*/
private static final String ENCODING="gbk";//字符集GBK
/**
* @author HXS
* @date 2012-12-19
* @todo TODO
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("发送到服务端的请求报文内容:");
Map requestParam=new HashMap();
requestParam.put("umCode",UMCODE);//出单账号
requestParam.put("policyNo",POLICYNO);//保单号
requestParam.put("validateCode",VALIDATECODE);//保单验真码
requestParam.put("isSeperated",ISSEPERATED);//如果是个单,填写空;
// requestParam.put("TransID",TransID);//出单账号
// requestParam.put("requestId",requestId);
Calendar calendar=Calendar.getInstance();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String curTime= sdf.format(calendar.getTime());
String data=UMCODE+POLICYNO+VALIDATECODE+ISSEPERATED+curTime;//待签名参数顺序不能变化
System.out.println("待签名内容:"+data);
String cipherText=signData(data,KEYSTORE_FILENAME,KEYSTORE_PASSWORD,KEYSTORE_ALIAS);//签名
System.out.println("签名结果:"+cipherText);//签名结果
requestParam.put("curTime",curTime);//时间戳
requestParam.put("cipherText",cipherText);
sendMsgToPingAn(requestParam); //发送报文到平安
System.out.println("接收服务端返回处理结束,文件路径:"+FILE_PATH);
}
/**
* 发送请求报文到服务端并接收服务端的返回结果
* @author HXS
* @date 2012-12-19
* @todo TODO
* @param requestMsg
* @return 返回结果
*/
private static void sendMsgToPingAn(Map requestMap)
{
String responseMsg="";
byte[] pdfStream=null;
String type="HTML";
try {
HttpClient httpClient = new DefaultHttpClient();
List paramList=new ArrayList();
paramList.add(new BasicNameValuePair("umCode",(String)requestMap.get("umCode")));
paramList.add(new BasicNameValuePair("policyNo",(String)requestMap.get("policyNo")));
paramList.add(new BasicNameValuePair("validateCode",(String)requestMap.get("validateCode")));
paramList.add(new BasicNameValuePair("curTime",(String)requestMap.get("curTime")));
paramList.add(new BasicNameValuePair("isSeperated",(String)requestMap.get("isSeperated")));
paramList.add(new BasicNameValuePair("cipherText",(String)requestMap.get("cipherText")));
paramList.add(new BasicNameValuePair("TransID",(String)requestMap.get("TransID")));
paramList.add(new BasicNameValuePair("requestId",(String)requestMap.get("requestId")));
//如果是服务端内部网络测试,需要使用代理方能请求到测试环境
((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(new AuthScope("10.36.232.18",80), new UsernamePasswordCredentials("", ""));
HttpHost proxy = new HttpHost("10.36.232.18", 8080);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpPost httpPost = new HttpPost(PINGANURL);
StringEntity entity;
entity = new UrlEncodedFormEntity(paramList, ENCODING);
httpPost.setEntity(entity);
System.out.println("正在发送交易..." );
HttpResponse httpResponse=httpClient.execute(httpPost);//发送请求到服务端
HttpEntity httpEntity=httpResponse.getEntity();//获取返回内容
Header[] headers=httpResponse.getHeaders("Content-type");//获取返回类型
for(int i=0;i<headers.length;i++)
{
String typeValue=headers[i].getValue();
if(typeValue!=null&&typeValue.toUpperCase().indexOf("PDF")>=0)//如果是pdf类型,下载后的文件是pdf类型
{
type="PDF";
break;
}
}
if(httpEntity!=null)
{
pdfStream=EntityUtils.toByteArray(httpEntity);//获取返回内容
String fileName="";
String curTime=(String)requestMap.get("curTime");
curTime=curTime.replaceAll(":", "");//冒号不能作为文件名
if(type.equals("PDF"))
{
fileName=FILE_PATH+curTime+".pdf";
}
else
{
fileName=FILE_PATH+curTime+".html";
}
OutputStream os=new FileOutputStream(new File(fileName));//输出内容到文件
os.write(pdfStream);
os.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 签名算法
* @author HXS
* @date 2012-7-2
* @todo TODO
* @param data 需要签名的内容
* @param keyStoreFileName 含私钥的文件
* @param keyStorePassword 含私钥文件的密码
* @param keyStoreAlias 别名
* @return
*/
public static String signData(String data,String keyStoreFileName,String keyStorePassword,String keyStoreAlias)
{
KeyStore keyStore;
byte[] signRstByte=null;
String signValue="";
String keystoreType="";
try {
if(keyStoreFileName.toUpperCase().indexOf("PFX")>=0)//判断证书文件的格式
{
keystoreType="PKCS12";
}
else
{
keystoreType="JKS";
}
keyStore = KeyStore.getInstance(keystoreType);//获取JKS证书实例
FileInputStream in=new FileInputStream(keyStoreFileName);//获取证书文件流
char[]pwdChar=keyStorePassword.toCharArray();//证书密码
keyStore.load(in, pwdChar);//加载证书到keystore中
PrivateKey privateKey=(PrivateKey)keyStore.getKey(keyStoreAlias, pwdChar);//从证书中获取私钥
Signature sign=Signature.getInstance("SHA1WithRSA");//SHA1WithRSA签名算法
sign.initSign(privateKey);//设置私钥
sign.update(data.getBytes());//设置明文
signRstByte=sign.sign();//加密
BASE64Encoder encoder=new BASE64Encoder();
signValue=encoder.encodeBuffer(signRstByte);//BASE64编码
//System.out.println("签名并编码后的内容signValue=="+signValue);
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return signValue;
}
}