集册 Java实例教程 获取文件SHA256

获取文件SHA256

欢马劈雪     最近更新时间:2020-01-02 10:19:05

916
获取文件SHA 256
/**来自 n o w j a v a . c o m**/

// Licensed under the Apache License, Version 2.0 (the "License");

//package com.nowjava;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.security.MessageDigest;


public class Main {

    public static String getFileSHA256(File file) {

        String str = "";

        try {

            str = getHash(file, "SHA-256");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return str;
        /** 
        来 自 
        N o w J a v a . c o m - 时  代  Java
        **/

    }


    private static String getHash(File file, String hashType)

            throws Exception {

        InputStream fis = new FileInputStream(file);

        byte buffer[] = new byte[1024];

        MessageDigest md5 = MessageDigest.getInstance(hashType);

        for (int numRead = 0; (numRead = fis.read(buffer)) > 0;) {

            md5.update(buffer, 0, numRead);

        }


        fis.close();

        return toHexString(md5.digest());

    }


    private static String toHexString(
展开阅读全文