Compute the md5 hash of a InputStream. - Java Security

Java examples for Security:MD5

Description

Compute the md5 hash of a InputStream.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

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

public class Main {
    /**/*  w  ww  .j ava  2 s.c  om*/
     * Compute the md5 hash of a InputStream.
     *
     * @param fis
     * the InputStream
     * @throws IOException
     * when there are problems reading the stream
     * @throws NoSuchAlgorithmException
     * should not bother to catch this exception
     * @return a MessageDigest
     */
    private static MessageDigest computeMd5MessageDigest(
            final InputStream fis) throws IOException,
            NoSuchAlgorithmException {
        int numRead;
        final int chunk = 1024;
        MessageDigest complete = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[chunk];
        do {
            numRead = fis.read(buffer, 0, chunk);
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        return complete;
    }
}

Related Tutorials