计算微信下载回单文件的哈希值,以确认下载账单数据的完整性

简介: 微信回单文件的哈希值,是微信支付为商户下载的电子回单文件生成的一个固定长度且唯一的字符串,也常被称为“数字指纹”。它主要用于验证回单文件的完整性和真实性。

大家好,我是小悟。


微信回单文件的哈希值,是微信支付为商户下载的电子回单文件生成的一个固定长度且唯一的字符串,也常被称为“数字指纹”。它主要用于验证回单文件的完整性和真实性。


可靠的哈希函数具有“雪崩效应”,即原始数据哪怕只发生一个比特的改变,计算出的哈希值也会截然不同。这使得它极其灵敏,能够有效发现文件的任何改动。


处理微信的回单文件并计算其哈希值,通常涉及获取文件、选择算法和实际计算几个步骤。


1. 基础版本 - 计算文件MD5和SHA-256

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.HexFormat;
public class WechatBillDigest {
    /**
     * 计算文件的MD5摘要值
     */
    public static String calculateMD5(String filePath) throws Exception {
        return calculateDigest(filePath, "MD5");
    }
    /**
     * 计算文件的SHA-256摘要值
     */
    public static String calculateSHA256(String filePath) throws Exception {
        return calculateDigest(filePath, "SHA-256");
    }
    /**
     * 通用摘要计算方法
     */
    private static String calculateDigest(String filePath, String algorithm) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }
        }
        byte[] hashBytes = digest.digest();
        return HexFormat.of().formatHex(hashBytes);
    }
}

2. 完整工具类(支持多种算法)

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public class WechatBillDigestUtil {
    public enum DigestAlgorithm {
        MD5("MD5"),
        SHA1("SHA-1"),
        SHA256("SHA-256"),
        SHA512("SHA-512");
        private final String algorithm;
        DigestAlgorithm(String algorithm) {
            this.algorithm = algorithm;
        }
        public String getAlgorithm() {
            return algorithm;
        }
    }
    /**
     * 计算微信回单文件的摘要值
     */
    public static String calculateDigest(File file, DigestAlgorithm algorithm) 
            throws NoSuchAlgorithmException, IOException {
        if (!file.exists()) {
            throw new IOException("文件不存在: " + file.getAbsolutePath());
        }
        if (!file.isFile()) {
            throw new IOException("路径不是文件: " + file.getAbsolutePath());
        }
        MessageDigest digest = MessageDigest.getInstance(algorithm.getAlgorithm());
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }
        }
        byte[] hashBytes = digest.digest();
        return HexFormat.of().formatHex(hashBytes);
    }
    /**
     * 批量计算多种摘要值
     */
    public static void calculateAllDigests(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("文件不存在: " + filePath);
            return;
        }
        System.out.println("文件: " + file.getName());
        System.out.println("大小: " + file.length() + " 字节");
        System.out.println("最后修改: " + new java.util.Date(file.lastModified()));
        System.out.println("----------------------------------------");
        for (DigestAlgorithm algorithm : DigestAlgorithm.values()) {
            try {
                String digest = calculateDigest(file, algorithm);
                System.out.printf("%-8s: %s%n", algorithm.name(), digest);
            } catch (Exception e) {
                System.out.printf("%-8s: 计算失败 - %s%n", algorithm.name(), e.getMessage());
            }
        }
    }
}

3. 带进度显示的高级版本

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
public class WechatBillDigestWithProgress {
    /**
     * 带进度显示的文件摘要计算
     */
    public static String calculateDigestWithProgress(String filePath, String algorithm) 
            throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("文件不存在: " + filePath);
        }
        long fileSize = file.length();
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            long totalRead = 0;
            long lastProgress = -1;
            System.out.println("开始计算文件摘要...");
            System.out.println("文件大小: " + formatFileSize(fileSize));
            while ((bytesRead = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
                totalRead += bytesRead;
                // 显示进度(每10%更新一次)
                int progress = (int) ((totalRead * 100) / fileSize);
                if (progress != lastProgress && progress % 10 == 0) {
                    System.out.printf("计算进度: %d%%%n", progress);
                    lastProgress = progress;
                }
            }
            System.out.println("计算完成: 100%");
        }
        byte[] hashBytes = digest.digest();
        return bytesToHex(hashBytes);
    }
    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
    /**
     * 格式化文件大小
     */
    private static String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) 
                + " " + units[digitGroups];
    }
}

4. 使用示例

public class WechatBillDigestExample {
    public static void main(String[] args) {
        String filePath = "path/to/wechat/bill.csv"; // 替换为实际文件路径
        try {
            // 方法1: 基础使用
            String md5 = WechatBillDigest.calculateMD5(filePath);
            String sha256 = WechatBillDigest.calculateSHA256(filePath);
            System.out.println("MD5: " + md5);
            System.out.println("SHA-256: " + sha256);
            System.out.println();
            // 方法2: 使用工具类计算所有摘要
            WechatBillDigestUtil.calculateAllDigests(filePath);
            System.out.println();
            // 方法3: 带进度显示
            String digestWithProgress = WechatBillDigestWithProgress
                    .calculateDigestWithProgress(filePath, "SHA-256");
            System.out.println("最终摘要值: " + digestWithProgress);
        } catch (Exception e) {
            System.err.println("计算摘要时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

5. Maven依赖(如果需要第三方库)

<dependencies>
    <!-- Apache Commons Codec 提供更多摘要算法支持 -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.16.0</version>
    </dependency>
</dependencies>

多种算法支持:MD5、SHA-1、SHA-256、SHA-512


大文件优化:使用缓冲区读取,避免内存溢出


进度显示:可显示计算进度


异常处理:完善的错误处理机制


格式规范:输出标准的十六进制字符串


计算微信下载回单文件的哈希值,以确认下载账单数据的完整性.jpg


谢谢你看我的文章,既然看到这里了,如果觉得不错,随手点个赞、转发、在看三连吧,感谢感谢。那我们,下次再见。


您的一键三连,是我更新的最大动力,谢谢


山水有相逢,来日皆可期,谢谢阅读,我们再会


我手中的金箍棒,上能通天,下能探海

相关文章
|
7月前
|
NoSQL Java MongoDB
Spring Boot 整合 MongoDB 最佳实践:CRUD、分页、事务、索引全覆盖
Spring Data MongoDB提供了简洁的API,让开发者能够专注于业务逻辑,快速构建高性能的应用。通过合理使用MongoDB的特性,可以充分发挥其文档数据库的优势。
215 6
|
8月前
|
监控 负载均衡 Dubbo
SpringBoot整合Dubbo,构建高性能分布式系统
Dubbo是阿里巴巴开源的一款高性能、轻量级的 Java RPC 框架,主要功能包括:面向接口的远程方法调用、智能负载均衡、服务自动注册与发现、高可用性、运行期流量调度、可视化的服务治理。
496 13
|
7月前
|
监控 Java 定位技术
SpringBoot深度整合高德地图,构建高性能位置服务
高德地图是中国领先的数字地图内容、导航和位置服务解决方案提供商,由阿里巴巴集团控股。它提供了全面的地图服务。
368 0
|
8月前
|
存储 缓存 负载均衡
SpringBoot整合Zookeeper,实现分布式集群部署
Zookeeper是一个分布式的、开源的分布式应用程序协调服务,是Google的Chubby一个开源的实现。它提供了一组简单的原语,使得分布式应用能够基于这些原语实现更高层次的服务。
762 4
|
9月前
|
安全 Java 数据库连接
SpringBoot动态脱敏实战,从注解到AOP的优雅打码术
你的“隐私部位”的数据,在系统中裸奔。这简直比在公共场所穿皇帝的新衣还尴尬!数据脱敏就是给这些敏感数据穿上得体的“小内裤”,让它们在需要展示的时候既能完成工作,又不至于春光乍泄。
631 4
|
11月前
|
移动开发 前端开发 Java
微信直连商户公众号 JSAPI 支付,详细教程+源码
JSAPI 支付用于微信公众号内的网页调起微信收银台,常见于在公众号菜单、文章页或 H5 活动页中完成支付。该方式依赖微信内置浏览器环境,非微信浏览器无法调起。
1087 1
|
12月前
|
Java 关系型数据库 Docker
Docker + Spring Boot:天生一对的完美部署
使用Docker部署Spring Boot项目能极大简化环境配置和应用分发。要将Spring Boot项目部署到Docker,主要流程是:准备项目、创建Docker镜像、运行Docker容器。
635 0
|
7月前
|
小程序 前端开发 开发工具
手机APP打开微信实现方案
在手机APP中实现跳转到微信应用的功能,主要用于:分享内容到微信好友或朋友圈,微信登录授权,微信支付,打开特定微信小程序。
340 4
|
7月前
|
Web App开发 移动开发 监控
手机H5页面直接打开APP实现方案
在移动端H5页面中,当用户点击"打开APP"按钮时:如果用户已安装APP,直接打开APP并跳转到指定页面,如果用户未安装APP,引导用户到应用商店下载,支持iOS和Android系统。
767 3
|
7月前
|
Web App开发 监控 前端开发
手机APP扫码上传图片到PC网站端实现方案
这种扫码上传方案特别适合需要频繁在手机和PC间传输图片的场景,结合了手机的便捷性和PC的处理能力,提供了良好的用户体验。
425 0