Java Hash Calculate getHashMD5(File file)

Here you can find the source of getHashMD5(File file)

Description

Generates MD5 hash for a given file.

License

Open Source License

Parameter

Parameter Description
file a parameter

Declaration

public static String getHashMD5(File file) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**//  ww w  .  j  a v  a  2s  .  c  o m
     * Generates MD5 hash for a given file.
     * 
     * @param file
     * @return
     */
    public static String getHashMD5(File file) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);

            byte[] dataBytes = new byte[1024];

            int nread = 0;

            while ((nread = fis.read(dataBytes)) != -1) {
                md.update(dataBytes, 0, nread);
            }

            fis.close();

            byte[] mdbytes = md.digest();

            // convert the byte to hex format method 1
            StringBuffer sb = new StringBuffer();

            for (int i = 0; i < mdbytes.length; i++) {
                sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. getHashChars(byte[] bytes)
  2. getHashedPassword(String plainPassword)
  3. getHashFromString(String str)
  4. getHashInstance(final String alg)
  5. getHashKey(String input)
  6. getHashMD5(String arg)
  7. getHashMD5(String str)
  8. getHashMD5(String text)
  9. getHashMDFive(String str)