Java MD5 Sum md5sum(File library)

Here you can find the source of md5sum(File library)

Description

mdsum

License

Open Source License

Declaration

public static String md5sum(File library) 

Method Source Code

//package com.java2s;
/* Copyright (c) 2013 Jesper ?qvist <jesper@llbit.se>
 *
 * This file is part of Chunky.//from www  .j  a v  a  2  s  .  co m
 *
 * Chunky is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Chunky is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Chunky.  If not, see <http://www.gnu.org/licenses/>.
 */

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 {
    private static byte[] NIBBLE_TO_HEX = "0123456789ABCDEF".getBytes();

    public static String md5sum(File library) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            FileInputStream in = new FileInputStream(library);
            DigestInputStream dis = new DigestInputStream(in, digest);
            byte[] buf = new byte[2048];
            int n;
            do {
                n = dis.read(buf);
            } while (n != -1);
            in.close();
            return byteArrayToHexString(digest.digest());
        } catch (IOException e) {
            return "md5 compute error: " + e.getMessage();
        } catch (NoSuchAlgorithmException e) {
            return "md5 compute error: " + e.getMessage();
        }
    }

    /**
     * Inspired by Real's How To: http://www.rgagnon.com/javadetails/java-0596.html
     * @param array
     * @return Hexadecimal string representation of the input bytes
     */
    public static String byteArrayToHexString(byte[] array) {
        byte[] hexdigits = new byte[array.length * 2];
        for (int i = 0; i < array.length; ++i) {
            hexdigits[i * 2] = NIBBLE_TO_HEX[(array[i] & 0xF0) >>> 4];
            hexdigits[i * 2 + 1] = NIBBLE_TO_HEX[array[i] & 0xF];
        }
        return new String(hexdigits);
    }
}

Related

  1. MD5Sum(byte[] par1Data)
  2. md5sum(File f)
  3. md5sum(File f, char[] cbuf, MessageDigest digest, byte[] bbuf)
  4. md5sum(File file)
  5. md5sum(File file)
  6. md5sum(InputStream file)
  7. md5sum(InputStream in)
  8. md5sum(String data)
  9. md5sum(String input)