Skip to content
Open
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
35 changes: 35 additions & 0 deletions docs/WECHAT_PAY_V3_SM2_SIGNATURES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# 微信支付 APIv3:SM2 请求签名与同步响应验签

此能力只覆盖 **APIv3 HTTP 请求签名**和**同步 HTTP 响应验签**(SDK 原本验签的成功 JSON 响应),不是完整国密接入。没有响应签名类型头时仍按 RSA 验证。

## 使用预加载的国密平台证书

参照[微信支付官方 SDK 国密示例](https://github.com/wechatpay-apiv3/wechatpay-java/blob/main/shangmi/README.md#使用国密-sdk),在可信渠道取得对应的微信支付 **SM2 平台证书**,在应用启动时预加载。商户 SM2 私钥用于签名,微信支付平台证书用于验签,两者不可混用。

下面是 WxJava 手动构造 HTTP 客户端的入口。示例只使用本地预加载证书,不触发自动下载。生产环境应在证书到期前从可信渠道更新本地证书并重建客户端;不要关闭默认的响应时间戳检查。

```java
CertificateFactory factory = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
X509Certificate platformCert;
try (InputStream in = Files.newInputStream(platformCertPath)) {
platformCert = (X509Certificate) factory.generateCertificate(in);
platformCert.checkValidity();
}

try (CloseableHttpClient client = WxPayV3HttpClientBuilder.create()
.withMerchant(mchId, merchantCertSerialNo, merchantSm2PrivateKey)
.withValidator(new WxPayValidator(new CertificatesVerifier(Collections.singletonList(platformCert))))
.build()) {
// 执行适用的 APIv3 同步 HTTP 请求;响应的证书序列号应与配置匹配。
}
```

此路径用本地模拟平台证书和 HTTP 应答验证,尚未与真实国密商户联调。**不要把 `WxPayConfig.fullPublicKeyModel` 当作已验证的国密商户配置**:[普通微信支付公钥模式](https://pay.wechatpay.cn/doc/v3/merchant/4013053249)记录的是 RSA 公钥和 `PUB_KEY_ID`。本项目的独立 SM2 公钥测试使用的是模拟密钥,不能证明微信支付会为国密商户提供对应的独立公钥和 ID。

## 暂不支持

- **自动下载或轮换国密平台证书**:官方接口需选择 `algorithm_type=SM2`,证书数据需要 SM4-GCM 解密。SDK 的普通证书自动更新路径未增加这两项能力。
- **国密异步回调**:普通支付和分账等回调的国密验签和 SM4-GCM 解密不在本阶段范围内。
- **国密敏感字段加解密**:属于独立能力。本阶段不要把需要该能力的业务视为已适配。

参考:[微信支付国密指引](https://pay.wechatpay.cn/doc/v3/merchant/4012076194) · [国密证书和密钥](https://pay.wechatpay.cn/doc/v3/merchant/4012076002)。
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,18 @@ public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key,

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

/** {@inheritDoc} */
@Override
public boolean verify(String serialNumber, byte[] message, String signature, String signatureType) {
checkAndAutoUpdateCert();
if (verifier == null) {
log.warn("No valid certificate available for verification");
return false;
}
return verifier.verify(serialNumber, message, signature);
return verifier.verify(serialNumber, message, signature, signatureType);
}

/**
Expand Down
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,20 @@
public interface Verifier {
boolean verify(String serialNumber, byte[] message, String signature);

/**
* 按响应头指定的签名类型验签。仅实现三参数方法的旧验签器默认只处理 RSA;
* 支持其他算法的验签器须覆盖此方法。
*
* @param serialNumber 证书或公钥序列号
* @param message 待验签消息
* @param signature Base64 编码的签名
* @param signatureType 微信支付签名类型;为空时按 RSA 处理
* @return 验签成功时返回 true
*/
default boolean verify(String serialNumber, byte[] message, String signature, String signatureType) {
return (signatureType == null || WechatPaySignature.RSA_TYPE.equals(signatureType))
&& 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
Loading