集册 Java实例教程 获取文件SHA 512

获取文件SHA 512

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

489
获取文件SHA 512

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

//package com.nowjava;

import java.io.File;/*n o w j a v a . c o m - 时  代  Java*/

import java.io.FileInputStream;

import java.io.InputStream;

import java.security.MessageDigest;


public class Main {

    public static String getFileSHA512(File file) {

        String str = "";

        try {

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

        } catch (Exception e) {

            e.printStackTrace();
            /**来自 
             时 代 J a v a - nowjava.com**/

        }

        return str;

    }


    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(
展开阅读全文