无关风月
22 小时以前 5dc40fcd64b0513150f1d8335ab849e6d8cdc28e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.dsh.account.util.wx;
 
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
 
public class WeChatV3SignUtil {
 
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
 
    /**
     * 从 PEM 文件中读取私钥内容
     */
    public static PrivateKey loadPrivateKeyFromPem(String pemFilePath) throws Exception {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(pemFilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.startsWith("-----") && !line.endsWith("-----")) {
                    sb.append(line);
                }
            }
        }
 
        byte[] pkcs8Bytes = Base64.getDecoder().decode(sb.toString());
 
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        return kf.generatePrivate(keySpec);
    }
 
    /**
     * 构造待签名字符串(按 key 字典序排序)
     */
    public static String buildSignMessage(Map<String, Object> map) {
        List<String> keys = new ArrayList<>(map.keySet());
//        Collections.sort(keys);
 
        StringBuilder sb = new StringBuilder();
 
        sb.append(map.get("appid")).append("\n");
        sb.append(map.get("timestamp")).append("\n");
        sb.append(map.get("noncestr")).append("\n");
        sb.append(map.get("prepayid")).append("\n");
        return sb.toString();
    }
 
    /**
     * 使用商户私钥生成签名(SHA256withRSA + Base64)
     */
    public static String signWithPrivateKey(String message, String privateKeyPath) throws Exception {
        PrivateKey privateKey = loadPrivateKeyFromPem(privateKeyPath);
 
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(message.getBytes(StandardCharsets.UTF_8));
        byte[] signedBytes = signature.sign();
 
        return Base64.getEncoder().encodeToString(signedBytes);
    }
}