Java Digest File digestFile(File file, String algorithm)

Here you can find the source of digestFile(File file, String algorithm)

Description

digest File

License

Apache License

Declaration

public static byte[] digestFile(File file, String algorithm) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static byte[] digestFile(File file, String algorithm) {
        if (file == null)
            return null;
        FileInputStream fis = null;
        DigestInputStream digestInputStream;
        try {/*from  ww w .  j  a va  2 s . c o  m*/
            fis = new FileInputStream(file);
            MessageDigest md = MessageDigest.getInstance(algorithm);
            digestInputStream = new DigestInputStream(fis, md);
            byte[] buffer = new byte[256 * 1024];
            while (true) {
                if (!(digestInputStream.read(buffer) > 0))
                    break;
            }
            md = digestInputStream.getMessageDigest();
            return md.digest();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] digest(byte[] data, String algorithm) {
        if (data == null || data.length <= 0) {
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(data);
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. digestFile(File file)
  2. digestFile(String filename, String algorithm)