Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import me.chanjar.weixin.common.error.WxRuntimeException;

import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
Expand All @@ -25,14 +26,16 @@ public CertificatesVerifier(List<X509Certificate> list) {
}
}

private boolean verify(X509Certificate certificate, byte[] message, String signature) {
private boolean verify(X509Certificate certificate, byte[] message, String signature, String signatureType) {
try {
Signature sign = Signature.getInstance("SHA256withRSA");
Signature sign = WechatPaySignature.create(signatureType);
sign.initVerify(certificate);
sign.update(message);
return sign.verify(Base64.getDecoder().decode(signature));
} catch (InvalidAlgorithmParameterException e) {
throw new WxRuntimeException("签名参数无效", e);
} catch (NoSuchAlgorithmException e) {
throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e);
throw new WxRuntimeException("当前Java环境不支持签名算法", e);
} catch (SignatureException e) {
throw new WxRuntimeException("签名验证过程发生了错误", e);
} catch (InvalidKeyException e) {
Expand All @@ -42,8 +45,13 @@ private boolean verify(X509Certificate certificate, byte[] message, String signa

@Override
public boolean verify(String serialNumber, byte[] message, String signature) {
return verify(serialNumber, message, signature, WechatPaySignature.RSA_TYPE);
}

@Override
public boolean verify(String serialNumber, byte[] message, String signature, String signatureType) {
BigInteger val = new BigInteger(serialNumber, 16);
return certificates.containsKey(val) && verify(certificates.get(val), message, signature);
return certificates.containsKey(val) && verify(certificates.get(val), message, signature, signatureType);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import me.chanjar.weixin.common.error.WxRuntimeException;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
Expand All @@ -22,18 +23,36 @@ public PrivateKeySigner(String serialNumber, PrivateKey privateKey) {
@Override
public SignatureResult sign(byte[] message) {
try {
Signature sign = Signature.getInstance("SHA256withRSA");
String schema = getSchema();
Signature sign = WechatPaySignature.create(schema);
sign.initSign(privateKey);
sign.update(message);

return new SignatureResult(
Base64.getEncoder().encodeToString(sign.sign()), certificateSerialNumber);
} catch (InvalidAlgorithmParameterException e) {
throw new WxRuntimeException("签名参数无效", e);
} catch (NoSuchAlgorithmException e) {
throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e);
throw new WxRuntimeException("当前Java环境不支持" + getSignatureAlgorithm(), e);
} catch (SignatureException e) {
throw new WxRuntimeException("签名计算失败", e);
} catch (InvalidKeyException e) {
throw new WxRuntimeException("无效的私钥", e);
}
}

@Override
public String getSchema() {
return isSm2Key() ? WechatPaySignature.SM2_TYPE : WechatPaySignature.RSA_TYPE;
}

private boolean isSm2Key() {
String algorithm = privateKey.getAlgorithm();
return "EC".equalsIgnoreCase(algorithm) || "ECDSA".equalsIgnoreCase(algorithm)
|| "SM2".equalsIgnoreCase(algorithm);
}

private String getSignatureAlgorithm() {
return isSm2Key() ? "SM3withSM2" : "SHA256withRSA";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,15 @@ public void setOtherVerifier(Verifier verifier) {

@Override
public boolean verify(String serialNumber, byte[] message, String signature) {
return verify(serialNumber, message, signature, WechatPaySignature.RSA_TYPE);
}

@Override
public boolean verify(String serialNumber, byte[] message, String signature, String signatureType) {
// 如果序列号不为空且不包含"PUB_KEY_ID"且有证书验证器,先尝试证书验证
if (serialNumber != null && !serialNumber.contains("PUB_KEY_ID") && this.certificateVerifier != null) {
try {
if (this.certificateVerifier.verify(serialNumber, message, signature)) {
if (this.certificateVerifier.verify(serialNumber, message, signature, signatureType)) {
return true;
}
} catch (Exception e) {
Expand All @@ -39,12 +44,14 @@ public boolean verify(String serialNumber, byte[] message, String signature) {
}
// 使用公钥验证(兜底方案,适用于公钥转账等场景)
try {
Signature sign = Signature.getInstance("SHA256withRSA");
Signature sign = WechatPaySignature.create(signatureType);
sign.initVerify(publicKey);
sign.update(message);
return sign.verify(Base64.getDecoder().decode(signature));
} catch (InvalidAlgorithmParameterException e) {
throw new WxRuntimeException("签名参数无效", e);
} catch (NoSuchAlgorithmException e) {
throw new WxRuntimeException("当前Java环境不支持SHA256withRSA", e);
throw new WxRuntimeException("当前Java环境不支持签名算法", e);
} catch (SignatureException e) {
throw new WxRuntimeException("签名验证过程发生了错误", e);
} catch (InvalidKeyException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
public interface Signer {
SignatureResult sign(byte[] message);

/**
* 获取用于 Authorization 请求头的认证类型。
*
* @return 微信支付认证类型
*/
default String getSchema() {
return "WECHATPAY2-SHA256-RSA2048";
}

class SignatureResult {
String sign;
String certificateSerialNumber;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@
public interface Verifier {
boolean verify(String serialNumber, byte[] message, String signature);

/**
* 按响应头指定的签名类型验签。
*
* @param serialNumber 证书或公钥序列号
* @param message 待验签消息
* @param signature Base64 编码的签名
* @param signatureType 微信支付签名类型;为空时按 RSA 处理
* @return 验签成功时返回 true
*/
default boolean verify(String serialNumber, byte[] message, String signature, String signatureType) {
return verify(serialNumber, message, signature);
}

X509Certificate getValidCertificate();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github.binarywang.wxpay.v3.auth;

import org.bouncycastle.jcajce.spec.SM2ParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Signature;

final class WechatPaySignature {
static final String RSA_TYPE = "WECHATPAY2-SHA256-RSA2048";
static final String SM2_TYPE = "WECHATPAY2-SM2-WITH-SM3";

private static final byte[] SM2_USER_ID =
"1234567812345678".getBytes(StandardCharsets.US_ASCII);
private static final Provider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider();

private WechatPaySignature() {
}

static Signature create(String signatureType)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
if (signatureType == null || RSA_TYPE.equals(signatureType)) {
return Signature.getInstance("SHA256withRSA");
}
if (SM2_TYPE.equals(signatureType)) {
Signature signature = Signature.getInstance("SM3withSM2", BOUNCY_CASTLE_PROVIDER);
signature.setParameter(new SM2ParameterSpec(SM2_USER_ID));
return signature;
}
throw new IllegalArgumentException("不支持的微信支付签名类型: " + signatureType);
}

static boolean isSupported(String signatureType) {
return signatureType == null || RSA_TYPE.equals(signatureType) || SM2_TYPE.equals(signatureType);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ protected String generateNonceStr() {

@Override
public final String getSchema() {
return "WECHATPAY2-SHA256-RSA2048";
return signer.getSchema();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,26 @@ public final boolean validate(CloseableHttpResponse response) throws IOException
}
Header serialNo = response.getFirstHeader("Wechatpay-Serial");
Header sign = response.getFirstHeader("Wechatpay-Signature");
Header signatureType = response.getFirstHeader("Wechatpay-Signature-Type");
Header timestamp = response.getFirstHeader("Wechatpay-TimeStamp");
Header nonce = response.getFirstHeader("Wechatpay-Nonce");

if (timestamp == null || nonce == null || serialNo == null || sign == null) {
return false;
}

String signatureTypeValue = signatureType == null ? null : signatureType.getValue();
if (!WechatPaySignature.isSupported(signatureTypeValue)) {
return false;
}

if (!isTimestampFresh(timestamp.getValue())) {
return false;
}

String message = buildMessage(response);
return verifier.verify(serialNo.getValue(), message.getBytes(StandardCharsets.UTF_8), sign.getValue());
return verifier.verify(serialNo.getValue(), message.getBytes(StandardCharsets.UTF_8), sign.getValue(),
signatureTypeValue);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class PemUtils {

Expand All @@ -34,9 +35,13 @@ public static PrivateKey loadPrivateKey(InputStream inputStream) {
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");

KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(
new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
byte[] encodedKey = Base64.getDecoder().decode(privateKey);
try {
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
} catch (InvalidKeySpecException e) {
return KeyFactory.getInstance("EC", new BouncyCastleProvider())
.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
}
} catch (NoSuchAlgorithmException e) {
throw new WxRuntimeException("当前Java环境不支持RSA", e);
} catch (InvalidKeySpecException e) {
Expand Down Expand Up @@ -74,8 +79,13 @@ public static PublicKey loadPublicKey(InputStream inputStream){
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s+", "");
return KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)));
byte[] encodedKey = Base64.getDecoder().decode(publicKey);
try {
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encodedKey));
} catch (InvalidKeySpecException e) {
return KeyFactory.getInstance("EC", new BouncyCastleProvider())
.generatePublic(new X509EncodedKeySpec(encodedKey));
}
} catch (NoSuchAlgorithmException e) {
throw new WxRuntimeException("当前Java环境不支持RSA", e);
} catch (InvalidKeySpecException e) {
Expand Down
Loading