|
| 1 | +package com.wechat.pay.contrib.apache.httpclient.auth; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.JsonNode; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.wechat.pay.contrib.apache.httpclient.Credentials; |
| 6 | +import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder; |
| 7 | +import com.wechat.pay.contrib.apache.httpclient.util.AesUtil; |
| 8 | +import com.wechat.pay.contrib.apache.httpclient.util.PemUtil; |
| 9 | +import java.io.ByteArrayInputStream; |
| 10 | +import java.io.IOException; |
| 11 | +import java.security.GeneralSecurityException; |
| 12 | +import java.security.cert.CertificateExpiredException; |
| 13 | +import java.security.cert.CertificateNotYetValidException; |
| 14 | +import java.security.cert.X509Certificate; |
| 15 | +import java.time.Duration; |
| 16 | +import java.time.Instant; |
| 17 | +import java.util.ArrayList; |
| 18 | +import java.util.List; |
| 19 | +import java.util.concurrent.locks.ReentrantLock; |
| 20 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 21 | +import org.apache.http.client.methods.HttpGet; |
| 22 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 23 | +import org.apache.http.util.EntityUtils; |
| 24 | +import org.slf4j.Logger; |
| 25 | +import org.slf4j.LoggerFactory; |
| 26 | + |
| 27 | +/** |
| 28 | + * 在原有CertificatesVerifier基础上,增加自动更新证书功能 |
| 29 | + */ |
| 30 | +public class AutoUpdateCertificatesVerifier implements Verifier { |
| 31 | + |
| 32 | + private static final Logger log = LoggerFactory.getLogger(AutoUpdateCertificatesVerifier.class); |
| 33 | + |
| 34 | + //证书下载地址 |
| 35 | + private static final String CertDownloadPath = "https://api.mch.weixin.qq.com/v3/certificates"; |
| 36 | + |
| 37 | + //上次更新时间 |
| 38 | + private volatile Instant instant; |
| 39 | + |
| 40 | + //证书更新间隔时间,单位为分钟 |
| 41 | + private int minutesInterval; |
| 42 | + |
| 43 | + private CertificatesVerifier verifier; |
| 44 | + |
| 45 | + private Credentials credentials; |
| 46 | + |
| 47 | + private byte[] apiV3Key; |
| 48 | + |
| 49 | + private ReentrantLock lock = new ReentrantLock(); |
| 50 | + |
| 51 | + //时间间隔枚举,支持一小时、六小时以及十二小时 |
| 52 | + public enum TimeInterval { |
| 53 | + OneHour(60), SixHours(60 * 6), TwelveHours(60 * 12); |
| 54 | + |
| 55 | + private int minutes; |
| 56 | + |
| 57 | + TimeInterval(int minutes) { |
| 58 | + this.minutes = minutes; |
| 59 | + } |
| 60 | + |
| 61 | + public int getMinutes() { |
| 62 | + return minutes; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key) { |
| 67 | + this(credentials, apiV3Key, TimeInterval.OneHour.getMinutes()); |
| 68 | + } |
| 69 | + |
| 70 | + public AutoUpdateCertificatesVerifier(Credentials credentials, byte[] apiV3Key, int minutesInterval) { |
| 71 | + this.credentials = credentials; |
| 72 | + this.apiV3Key = apiV3Key; |
| 73 | + this.minutesInterval = minutesInterval; |
| 74 | + //构造时更新证书 |
| 75 | + try { |
| 76 | + autoUpdateCert(); |
| 77 | + instant = Instant.now(); |
| 78 | + } catch (IOException | GeneralSecurityException e) { |
| 79 | + throw new RuntimeException(e); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + @Override |
| 84 | + public boolean verify(String serialNumber, byte[] message, String signature) { |
| 85 | + if (instant == null || Duration.between(instant, Instant.now()).toMinutes() >= minutesInterval) { |
| 86 | + if (lock.tryLock()) { |
| 87 | + try { |
| 88 | + autoUpdateCert(); |
| 89 | + //更新时间 |
| 90 | + instant = Instant.now(); |
| 91 | + } catch (GeneralSecurityException | IOException e) { |
| 92 | + log.warn("Auto update cert failed, exception = " + e); |
| 93 | + } finally { |
| 94 | + lock.unlock(); |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + return verifier.verify(serialNumber, message, signature); |
| 99 | + } |
| 100 | + |
| 101 | + private void autoUpdateCert() throws IOException, GeneralSecurityException { |
| 102 | + CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create() |
| 103 | + .withCredentials(credentials) |
| 104 | + .withValidator(verifier == null ? (response) -> true : new WechatPay2Validator(verifier)) |
| 105 | + .build(); |
| 106 | + |
| 107 | + HttpGet httpGet = new HttpGet(CertDownloadPath); |
| 108 | + httpGet.addHeader("Accept", "application/json"); |
| 109 | + |
| 110 | + CloseableHttpResponse response = httpClient.execute(httpGet); |
| 111 | + int statusCode = response.getStatusLine().getStatusCode(); |
| 112 | + String body = EntityUtils.toString(response.getEntity()); |
| 113 | + if (statusCode == 200) { |
| 114 | + List<X509Certificate> newCertList = deserializeToCerts(apiV3Key, body); |
| 115 | + if (newCertList.isEmpty()) { |
| 116 | + log.warn("Cert list is empty"); |
| 117 | + return; |
| 118 | + } |
| 119 | + this.verifier = new CertificatesVerifier(newCertList); |
| 120 | + } else { |
| 121 | + log.warn("Auto update cert failed, statusCode = " + statusCode + ",body = " + body); |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + |
| 126 | + /** |
| 127 | + * 反序列化证书并解密 |
| 128 | + */ |
| 129 | + private List<X509Certificate> deserializeToCerts(byte[] apiV3Key, String body) |
| 130 | + throws GeneralSecurityException, IOException { |
| 131 | + AesUtil decryptor = new AesUtil(apiV3Key); |
| 132 | + ObjectMapper mapper = new ObjectMapper(); |
| 133 | + JsonNode dataNode = mapper.readTree(body).get("data"); |
| 134 | + List<X509Certificate> newCertList = new ArrayList<>(); |
| 135 | + if (dataNode != null) { |
| 136 | + for (int i = 0, count = dataNode.size(); i < count; i++) { |
| 137 | + JsonNode encryptCertificateNode = dataNode.get(i).get("encrypt_certificate"); |
| 138 | + //解密 |
| 139 | + String cert = decryptor.decryptToString( |
| 140 | + encryptCertificateNode.get("associated_data").toString().replaceAll("\"", "") |
| 141 | + .getBytes("utf-8"), |
| 142 | + encryptCertificateNode.get("nonce").toString().replaceAll("\"", "") |
| 143 | + .getBytes("utf-8"), |
| 144 | + encryptCertificateNode.get("ciphertext").toString().replaceAll("\"", "")); |
| 145 | + |
| 146 | + X509Certificate x509Cert = PemUtil |
| 147 | + .loadCertificate(new ByteArrayInputStream(cert.getBytes("utf-8"))); |
| 148 | + try { |
| 149 | + x509Cert.checkValidity(); |
| 150 | + } catch (CertificateExpiredException | CertificateNotYetValidException e) { |
| 151 | + continue; |
| 152 | + } |
| 153 | + newCertList.add(x509Cert); |
| 154 | + } |
| 155 | + } |
| 156 | + return newCertList; |
| 157 | + } |
| 158 | +} |
0 commit comments