package com.njcn.gather.systemops.database.util;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;

/**
 * 文件校验工具。
 */
public final class DatabaseChecksumUtil {

    private DatabaseChecksumUtil() {
    }

    public static String sha256(Path path) {
        if (path == null || !Files.exists(path) || Files.isDirectory(path)) {
            return null;
        }
        try (InputStream inputStream = Files.newInputStream(path)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, length);
            }
            byte[] bytes = digest.digest();
            StringBuilder builder = new StringBuilder();
            for (byte item : bytes) {
                builder.append(String.format("%02x", item));
            }
            return builder.toString();
        } catch (Exception exception) {
            return null;
        }
    }
}
