Java 如何计算jar包的HASH哈希值

166 阅读1分钟

在做授权系统的时候用到了一个小功能发出来分享一下。

全部代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {

    public static void main(String[] args) {
        try {
            // 获取当前运行的 JAR 文件
            File jarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());

            // 计算 JAR 文件的哈希值(如 SHA-256)
            String hash = calculateJarHash(jarFile, "SHA-256");

            // 打印哈希值
            System.out.println("JAR 文件的 SHA-256 哈希值: " + hash);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String calculateJarHash(File jarFile, String algorithm) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            // 读取 JAR 文件并更新哈希计算
            try (InputStream is = new FileInputStream(jarFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    digest.update(buffer, 0, bytesRead);
                }
            }

            // 将哈希值转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest.digest()) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException | java.io.IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

本文由博客一文多发平台 OpenWrite 发布!