欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java文件完整性校验sha256

程序员文章站 2022-07-08 20:24:32
...

Java文件完整性校验sha256

  • pom依赖
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.12</version>
</dependency>
  • Java代码
    • 测试大概十个G文件处理时间大概需要50秒
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

/**
 * sha文件完整性校验
 *
 * @author xxx
 */
public class FileCheckSHA {

    private static final Logger logger = LoggerFactory.getLogger(FileCheckSHA.class);

    public static void main(String[] args) throws IOException {

        long startTime = System.currentTimeMillis();//记录开始时间
		
        File file = new File("C:\\Users\\xxx\\Desktop\\test.zip");
        String fileSHA256 = fileSHA256(file);
        System.out.println(fileSHA256);

        long endTime = System.currentTimeMillis();//记录结束时间
        float excTime = (float) (endTime - startTime) / 1000;
        int minutes = (int) (excTime / 60);
        int second = (int) (excTime % 60);
        logger.info("一共用时" + minutes + "分" + second + "秒 》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》");


        boolean b = checkFileSHA256(file, "8fbc38cfae2f49664d7bd2832d5a8316d59fab684b00781436216acddee50f96");
        System.out.println(b);
    }


    /**
     * 获取文件SHA256
     *
     * @param file
     * @return
     */
    public static String fileSHA256(File file) {
        String sha256Hex = null;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            sha256Hex = DigestUtils.sha256Hex(inputStream);
            return sha256Hex;
        } catch (IOException e) {
            logger.error("文件获取SHA256失败", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 检查文件的SHA256 是否正确
     *
     * @param file   文件
     * @param SHA256 SHA256结果值
     * @return
     */
    public static boolean checkFileSHA256(File file, String SHA256) {
        String sha256Hex = null;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            sha256Hex = DigestUtils.sha256Hex(inputStream);
            if (sha256Hex.equals(SHA256)) {
                return true;
            }
        } catch (IOException e) {
            logger.error("SHA256检查文件完整性失败", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}