收藏
回答

下载回执单使用SM3计算摘要得到的结果去对比查询电子回单返回的hashValue,出现不一致的情况

public static String downloadReceipt(PrivateKey privateKey, String platformCertSerialNo, JeePayDTO payData,
                                     String downloadUrl, String expectedHash, String settleNo) throws Exception {
    HttpUriRequest httpRequest = WechatConfigUtil.buildRequestForDownload("GET", downloadUrl, null, privateKey, payData.getMchSerialNo(), payData.getMchId(), platformCertSerialNo);

    try (CloseableHttpClient client = HttpClients.createDefault();
         CloseableHttpResponse response = client.execute(httpRequest)) {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            throw new ServiceException("下载电子回单失败, 响应: " + responseBody, HttpStatus.BUSINESS);
        }

        byte[] fileBytes;
        try (InputStream inputStream = response.getEntity().getContent();
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            fileBytes = baos.toByteArray();
        }

        String actualHash = computeHash(fileBytes);
        log.info("期望hash:{}", expectedHash);
        log.info("实际hash:{}", actualHash);
        // 校验hash值,确保文件完整性
        boolean isValid = expectedHash.equalsIgnoreCase(actualHash);
        if (!isValid) {
            throw new ServiceException("文件hash校验失败,文件可能不完整或被篡改!", HttpStatus.BUSINESS);
        }
        return "";
    }
}
private static String computeHash(byte[] data) {
    try {
        MessageDigest md = MessageDigest.getInstance("SM3");
        byte[] hash = md.digest(data);
        //转换为大写十六进制字符串
        StringBuilder hex = new StringBuilder();
        for (byte b : hash) {
            hex.append(String.format("%02X", b));
        }
        return hex.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("SM3算法不可用", e);
    }
}


回答关注问题邀请回答
收藏

2 个回答

登录 后发表内容