Skip to content
Merged
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,11 @@ cp -R skills/wxjava-* "${CODEX_HOME:-$HOME/.codex}/skills/"

</details>

### 小程序解密与 Bouncy Castle 依赖迁移

- `weixin-java-miniapp` 已移除公开方法 `WxMaCryptUtils.decryptAnotherWay`。解密微信小程序标准会话数据时,使用 `WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr)`。旧方法会将密钥补零至 16 字节的整数倍,并按 AES 的 16 字节分组处理 PKCS#7 填充。`decrypt` 使用原始 AES 密钥和微信的 32 字节填充规则。若业务依赖旧方法的补零或填充行为,应在应用侧保留等价实现,并用历史密文验证。
Comment thread
buaazyl marked this conversation as resolved.
Resolved
- `weixin-java-miniapp`、`weixin-java-pay`、`weixin-java-channel` 和 `weixin-java-store` 不再传递引入 Bouncy Castle。应用直接使用 BC API 时,请显式声明需要的 `org.bouncycastle` 依赖。若应用原先依赖 WxJava 注册名为 `BC` 的 JCA Provider,请改为在应用初始化时注册。

---

## 社区交流
Expand Down
4 changes: 0 additions & 4 deletions weixin-java-channel/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,6 @@
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
Expand Down
4 changes: 0 additions & 4 deletions weixin-java-miniapp/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,6 @@
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import me.chanjar.weixin.common.error.WxRuntimeException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import cn.binarywang.wx.miniapp.config.WxMaConfig;
import me.chanjar.weixin.common.util.crypto.PKCS7Encoder;
Expand Down Expand Up @@ -53,37 +49,6 @@ public static String decrypt(String sessionKey, String encryptedData, String ivS
}


/**
* AES解密.
*
* @param sessionKey session_key
* @param encryptedData 消息密文
* @param ivStr iv字符串
* @return 解密后的字符串
*/
public static String decryptAnotherWay(String sessionKey, String encryptedData, String ivStr) {
byte[] keyBytes = Base64.decodeBase64(sessionKey.getBytes(UTF_8));

int base = 16;
if (keyBytes.length % base != 0) {
int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
keyBytes = temp;
}

Security.addProvider(new BouncyCastleProvider());
Key key = new SecretKeySpec(keyBytes, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Base64.decodeBase64(ivStr.getBytes(UTF_8))));
return new String(cipher.doFinal(Base64.decodeBase64(encryptedData.getBytes(UTF_8))), UTF_8);
} catch (Exception e) {
throw new WxRuntimeException("AES解密失败!", e);
}
}

/**
* 使用用户加密 key 对数据进行 AES-128-CBC 解密(用于小程序加密网络通道).
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,14 @@ public class WxMaCryptUtilsTest {
private static final String ENCRYPT_KEY = "VI6BpyrK9XH4i4AIGe86tg==";
private static final String HEX_IV = "6003f73ec441c3866003f73ec441c386";

/**
* 验证使用会话密钥解密时按 32 字节分组去掉填充。
*/
@Test
public void testDecrypt() {
String sessionKey = "7MG7jbTToVVRWRXVA885rg==";
String encryptedData = "BY6VOgcWbwGcyrunK0ECWI8rnDsT69DucZ+M78tc1aL9aM/3bEAHFYd4fu7kRjWhD4YfjObw44T9vUqKyHIjbKs6hvtEasZZEIW35x4a91xVgN48ZqZ7MTQqUlP13kDUlkuwYh+/8g8yceu4kNbjowYrhihx+SV7CfjKCveJ7TSepr5Z7aLv1o+rfeelfOwn++WN/YoQsuZ6S3L4fWlWe5DAAUnFUI6cJvxxCohVzbrVXhyH2AqQdSjH2WnMYFeaGFIbcoxMznlk7oEwFn+hBj63dyT/swdYQfEdzuyCBmKXy8d6l1RKVX6Y65coTD8kIlbr+FKsqYrXVUIUBSwehqYuOdhYWZ9Bntl5DWU1oqzAPCnMn2cAIoQpQPKP7IGSxMOvCNAMhVXbE7BvnWuVuGF+AM5tXAa9IVUhcMImGwLQqm4iV5uBd+5OcFObh3A4VJk9iBCBWSkBHa/rV9CVoY0bFv2F9/2Hv82++Ybl274=";
String ivStr = "TarMFjnzHVxy8pdS93wQbw==";
System.out.println(WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr));
// System.out.println(WxMaCryptUtils.decryptAnotherWay(sessionKey, encryptedData, ivStr));
}

@Test
public void testDecryptAnotherWay() {
String encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ142dNCuabNPGBzlooOmB231qMM85d2/fV6ChevvXvQP8Hkue1poOFtnEtpyxVLW1zAo6/1Xx1COxFvrc2d7UL/lmHInNlxuacJXwu0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn/Hz7saL8xz+W//FRAUid1OksQaQx4CMs8LOddcQhULW4ucetDf96JcR3g0gfRK4PC7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns/8wR2SiRS7MNACwTyrGvt9ts8p12PKFdlqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYVoKlaRv85IfVunYzO0IKXsyl7JCUjCpoG20f0a04COwfneQAGGwd5oa+T8yO5hzuyDb/XcxxmK01EpqOyuxINew==";
String ivStr = "r7BXXKkLb8qrSNn05n0qiA==";
String sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";

assertThat(WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr))
.isEqualTo(WxMaCryptUtils.decryptAnotherWay(sessionKey, encryptedData, ivStr));
assertThat(WxMaCryptUtils.decrypt("AQIDBAUGBwgJCgsMDQ4PEA==",
"Znhd/z4nX37N0rS/GN8M8y3mlyV+izPMrJpQfPYoOz8=", "AAAAAAAAAAAAAAAAAAAAAA=="))
.isEqualTo("miniapp-test");
}

/**
Expand Down
5 changes: 0 additions & 5 deletions weixin-java-pay/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,6 @@
<artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
</dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,22 @@
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import lombok.RequiredArgsConstructor;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
Expand All @@ -34,6 +37,14 @@
*/
@RequiredArgsConstructor
public class EntPayServiceImpl implements EntPayService {
// DER AlgorithmIdentifier for rsaEncryption (1.2.840.113549.1.1.1), with NULL parameters.
private static final byte[] RSA_ALGORITHM_IDENTIFIER = {
0x30, 0x0d, 0x06, 0x09, 0x2a, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00
};

private static final OAEPParameterSpec BANK_OAEP_PARAMETERS =
new OAEPParameterSpec("SHA-1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);

private final WxPayService payService;

@Override
Expand Down Expand Up @@ -174,23 +185,105 @@ public EntPayResult toEmpPay(EntWxEmpPayRequest request) throws WxPayException {
return result;
}

/**
* 读取付款公钥并按照微信支付 V2 的 OAEP 规则加密字段。
*
* @param publicKeyFile 微信支付返回的 PEM 公钥文件,支持 PKCS#1 和 SPKI
* @param srcString 原始银行卡号或姓名
* @return Base64 编码的密文
* @throws WxPayException 公钥读取或字段加密失败时
*/
private String encryptRSA(File publicKeyFile, String srcString) throws WxPayException {
try {
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
try (PEMParser reader = new PEMParser(new FileReader(publicKeyFile))) {
final PublicKey publicKey = new JcaPEMKeyConverter().setProvider("BC")
.getPublicKey((SubjectPublicKeyInfo) reader.readObject());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypt = cipher.doFinal(srcString.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypt);
}
PublicKey publicKey = loadBankPublicKey(publicKeyFile.toPath());
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey, BANK_OAEP_PARAMETERS);
byte[] encrypt = cipher.doFinal(srcString.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypt);
} catch (Exception e) {
throw new WxPayException("加密出错", e);
}
}

/**
* 读取第一个 PEM 对象,兼容微信支付默认的 PKCS#1 公钥和 SPKI 公钥。
*
* @param path PEM 公钥文件路径
* @return RSA 公钥
* @throws IOException 文件无法读取或 PEM 边界无效时
* @throws GeneralSecurityException 公钥无法加载时
* @throws IllegalArgumentException PEM 内容不是有效的 Base64 时
*/
private PublicKey loadBankPublicKey(Path path) throws IOException, GeneralSecurityException {
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line;
do {
line = reader.readLine();
} while (line != null && !line.startsWith("-----BEGIN "));

String header = line == null ? "" : line.trim();
boolean pkcs1 = "-----BEGIN RSA PUBLIC KEY-----".equals(header);
if (!pkcs1 && !"-----BEGIN PUBLIC KEY-----".equals(header)) {
throw new IOException("无效的 RSA 公钥 PEM 头");
}
String footer = pkcs1 ? "-----END RSA PUBLIC KEY-----" : "-----END PUBLIC KEY-----";
StringBuilder encoded = new StringBuilder();
while ((line = reader.readLine()) != null && !line.startsWith(footer)) {
if (line.indexOf(':') < 0) {
encoded.append(line);
}
}
if (line == null) {
throw new IOException("缺少 RSA 公钥 PEM 结束标记");
}
byte[] der = Base64.getDecoder().decode(encoded.toString().replaceAll("\\s+", ""));
return KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(pkcs1 ? wrapPkcs1PublicKey(der) : der));
}
}

/**
* 将 PKCS#1 公钥放入 JDK 所需的 SubjectPublicKeyInfo 结构。
*
* @param pkcs1 DER 编码的 PKCS#1 公钥
* @return DER 编码的 SubjectPublicKeyInfo
*/
private byte[] wrapPkcs1PublicKey(byte[] pkcs1) {
byte[] bits = new byte[pkcs1.length + 1];
// DER BIT STRING 的首字节是未使用的位数,整字节数据的该值为零。
System.arraycopy(pkcs1, 0, bits, 1, pkcs1.length);

ByteArrayOutputStream content = new ByteArrayOutputStream();
content.write(RSA_ALGORITHM_IDENTIFIER, 0, RSA_ALGORITHM_IDENTIFIER.length);
writeDer(content, 0x03, bits);

ByteArrayOutputStream spki = new ByteArrayOutputStream();
writeDer(spki, 0x30, content.toByteArray());
return spki.toByteArray();
}

/**
* 写入一个 DER 标签及其定长内容。
*
* @param output 编码输出
* @param tag 单字节 DER 标签
* @param value 待写入的内容
*/
private void writeDer(ByteArrayOutputStream output, int tag, byte[] value) {
output.write(tag);
int length = value.length;
if (length < 128) {
output.write(length);
} else {
int bytes = (Integer.SIZE - Integer.numberOfLeadingZeros(length) + 7) / 8;
output.write(0x80 | bytes);
for (int shift = (bytes - 1) * 8; shift >= 0; shift -= 8) {
output.write(length >>> shift);
}
}
output.write(value, 0, length);
}

private File buildPublicKeyFile() throws WxPayException {
try {
String publicKeyStr = this.getPublicKey();
Expand Down
Loading
Loading