⽀付宝⽀付签名请求、解析demo
⼩编开发的时候就是被最终请求字段值编码坑了,同学们要谨记教训,要看清楚哪⾥值需要转义哪⾥不需要哇。
//获取到待签名的字符串,**这⾥字段的值不需要做编码**
维嘉龙丹妮public static String getSignContent(Map<String, String> sortedParams) {
StringBuffer content = new StringBuffer();
普通螺丝
List<String> keys = new ArrayList<String>(sortedParams.keySet());
Collections.sort(keys);
罗志祥杨丞琳不和int index = 0;
for (int i = 0; i < keys.size(); i++) {
String key = (i);
String value = (key);
if (StringUtils.areNotEmpty(key, value)) {
content.append((index == 0 ? "" : "&") + key + "=" + value);
index++;
}
}
String();
}
//使⽤RSA对请求数据签名。base64编码⾃⾏百度。**注意:最终的签名值需要Encoder⼀下**
public static String rsaSign(String content, String privateKey,
String charset) throws AlipayApiException {
try {
PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
new Bytes()));
java.security.Signature signature = java.security.Signature
.getInstance("SHA1WithRSA");
signature.initSign(priKey);
if (StringUtils.isEmpty(charset)) {
signature.Bytes());
} else {
signature.Bytes(charset));
}
byte[] signed = signature.sign();
return new deBase64(signed));
} catch (InvalidKeySpecException ie) {
throw new AlipayApiException("RSA私钥格式不正确,请检查是否正确配置了PKCS8格式的私钥", ie);
} catch (Exception e) {
throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
}
}
//拼接最终请求数据参数。这⾥和getSignContent()区别在与,签名的时候字段值不需要编码,最终的请求参数的字段值是需要编码的。
public static String createLinkString(Map<String, String> params) throws UnsupportedEncodingException {
魔兽世界好名字List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = (i);
String value = (key);
if (i == keys.size() - 1) {//拼接时,不包括最后⼀个&字符
prestr = prestr + key + "=" + de(value,StringHelp.UTF_8) + "";
} else {
prestr = prestr + key + "=" + de(value,StringHelp.UTF_8) + "&";
}
}
return prestr;
}
//验签,这⾥我⽤的是ras的签名。所以解签的时候也需要使⽤ras
public static boolean rsaCheck(String content, String sign, String publicKey, String charset) {
try {
sign = org.apachemons.place(sign, " ", "+");
PublicKey pubKey = getPublicKeyFromX509("RSA",
new Bytes()));张蕾的老公
java.security.Signature signature = java.security.Signature
.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
if (StringUtils.isEmpty(charset)) {
signature.Bytes());
} else {
signature.Bytes(charset));
sunshine 组合}
return signature.verify( Base64.Bytes()));
} catch (Exception e) {
throw new AlipayApiException(
"RSAcontent = " + content + ",sign=" + sign + ",charset = " + charset, e);
}
}
欧了