java 如何在Java中计算文件的哈希值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32032851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:31:51  来源:igfitidea点击:

How to calculate hash value of a file in Java?

javaarraysfile-iohash

提问by Abraham

I wrote the following program to calculate SHA-256 hash value of a string in Java:

我编写了以下程序来计算 Java 中字符串的 SHA-256 哈希值:

public class ToHash {

    public static void main(String[] args)  {

        byte[] data = "test".getBytes("UTF8");
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(data);
        System.out.println(new BASE64Encoder().encode(hash));

    }
}

Well, that works fine. In the next step I want to develop it in a way to accept a file and calculate its hash value. My solution is to read whole the file in a string array and the call the digest()method on that string array. But there are two problems :

嗯,这很好用。在下一步中,我想以一种接受文件并计算其哈希值的方式开发它。我的解决方案是在字符串数组中读取整个文件并调用该digest()字符串数组上的方法。但是有两个问题:

  1. I don't have any idea how to read whole the file into an array? Currently I think I must read it line by line and append an array with the new lines!

  2. Above methodology need a lot of memory for big files!

  1. 我不知道如何将整个文件读入数组?目前我想我必须一行一行地阅读它并用新行附加一个数组!

  2. 对于大文件,上述方法需要大量内存!



This is my current program to read a file:

这是我当前读取文件的程序:

public class ToHash {

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, FileNotFoundException, IOException {
        // TODO code application logic here

        // The name of the file to open.
        String fileName = "C:\Users\ghasemi\Desktop\1.png";
        BufferedReader br = null;

        try {

            String sCurrentLine;
            br = new BufferedReader(new FileReader(fileName));
            while ((sCurrentLine = br.readLine()) != null) {
                byte[] data = sCurrentLine.getBytes("UTF8");
                System.out.println(new BASE64Encoder().encode(data));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

It seems that there is no method for BufferedReaderobject to read whole the file with one call.

似乎没有方法让BufferedReader对象通过一次调用读取整个文件。

回答by user207421

You can read the file and calculate the value of the hash as you go.

您可以随时读取文件并计算哈希值。

    byte[] buffer= new byte[8192];
    int count;
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
    while ((count = bis.read(buffer)) > 0) {
        digest.update(buffer, 0, count);
    }
    bis.close();

    byte[] hash = digest.digest();
    System.out.println(new BASE64Encoder().encode(hash));

This doesn't assume anything about character sets or about the file fitting into memory, and it doesn't ignore line terminators either.

这不假设任何有关字符集或适合内存的文件,也不会忽略行终止符。

Or you can use a DigestInputStream.

或者你可以使用 DigestInputStream.