Java MD5 Stream computeMD5(InputStream inputStream)

Here you can find the source of computeMD5(InputStream inputStream)

Description

Compute MD5 for a stream

License

Open Source License

Parameter

Parameter Description
inputStream Stream to read

Exception

Parameter Description
NoSuchAlgorithmException If system not support MD5
IOException On reading stream issue

Return

MD5 of the stream

Declaration

public static String computeMD5(InputStream inputStream) throws NoSuchAlgorithmException, IOException 

Method Source Code

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

import java.io.IOException;
import java.io.InputStream;

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

public class Main {
    /**/*from ww  w .  j  a  v  a2s  .  c o  m*/
     * Compute MD5 for a stream
     * 
     * @param inputStream
     *           Stream to read
     * @return MD5 of the stream
     * @throws NoSuchAlgorithmException
     *            If system not support MD5
     * @throws IOException
     *            On reading stream issue
     */
    public static String computeMD5(InputStream inputStream) throws NoSuchAlgorithmException, IOException {
        final MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] temp = new byte[4096];

        int read = inputStream.read(temp);
        while (read >= 0) {
            md5.update(temp, 0, read);

            read = inputStream.read(temp);
        }

        inputStream.close();
        inputStream = null;

        temp = md5.digest();
        final StringBuffer stringBuffer = new StringBuffer();
        for (final byte b : temp) {
            read = b & 0xFF;
            stringBuffer.append(Integer.toHexString((read >> 4) & 0xF));
            stringBuffer.append(Integer.toHexString(read & 0xF));
        }
        temp = null;

        return stringBuffer.toString();
    }
}

Related

  1. computeMd5(InputStream is)
  2. computeMD5(InputStream message)
  3. computeMD5checksum(InputStream input)
  4. computeMd5Hash(InputStream is)