在做支付業務的時候,需要驗證資訊的正確性,所以選取用到了數位簽章,精簡如下:
私密金鑰簽名,公開金鑰驗證簽名.
業務平台(資訊傳送端):私密金鑰 用於對傳送資料進行簽名(sign)
支付平台(資訊接收端):公開金鑰 用於驗證簽名
業務平台:
// 參數產生String jsonString = "需傳遞的資料,請求資料";String paySign = RSA.sign(jsonString, "私密金鑰" ,"utf-8");paySign = URLEncoder.encode(paySign,"utf-8");respStr =URLUtil.doGet(PropertiesUtil.getUrl() + "/testApply/apply?"+URLEncoder.encode(jsonString,"utf-8")+"&sign="+paySign+"&signType=" + "RSA" +"&inputCharset=" + "utf-8");
支付平台:
//進行簽名驗證(paySign不需要decode,verify方法裡面有做)if(!RSA.verify(jsonString, paySign ,"公開金鑰", "utf-8")){logger.info("簽名驗證不通過");model.setCode(-1);model.setDesc("簽名驗證不通過");return model;}
get要求方法如下:
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; /** * 發送http請求,以get方式 * * @param url 請求url * @return * @throws IOException * @throws HttpException */ public static String doGet(String url) throws IOException, HttpException { try { HttpGet httpGet = new HttpGet(url); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse res = httpClient.execute(httpGet); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return EntityUtils.toString(res.getEntity()); } } catch (Exception e) { } return ""; }
此文演算法簽名和驗證簽名工具類:點擊開啟連結下載
有問題請指正,共同探討,感謝........