Java MD5 String md5(InputStream input)

Here you can find the source of md5(InputStream input)

Description

md

License

Apache License

Declaration

public static String md5(InputStream input) throws IOException 

Method Source Code


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

import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.google.common.base.Stopwatch;

public class Main {
    public static String md5(InputStream input) throws IOException {
        try {/*ww  w . ja  va 2 s . c  om*/
            return digest(input, "MD5");
        } catch (NoSuchAlgorithmException e) {
            // MD5 must be ok
            throw new RuntimeException(e);
        }
    }

    public static String digest(InputStream input, String algorithm) throws IOException, NoSuchAlgorithmException {
        Stopwatch sw = Stopwatch.createStarted();
        int bufferSize = 256 * 1024;
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        try (DigestInputStream digestInputStream = new DigestInputStream(input, messageDigest);) {
            byte[] buffer = new byte[bufferSize];
            while (digestInputStream.read(buffer) > 0) {
                ;
            }
            messageDigest = digestInputStream.getMessageDigest();
            byte[] resultByteArray = messageDigest.digest();
            return byteArrayToHex(resultByteArray);
        } finally {
            sw.stop();
        }
    }

    private static String byteArrayToHex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
            if (n < b.length - 1) {
                hs = hs + "";
            }
        }
        return hs;
    }
}

Related

  1. md5(final String s)
  2. md5(final String str)
  3. md5(final String string)
  4. md5(final String string)
  5. md5(final String text)
  6. md5(InputStream is)
  7. md5(java.lang.String message)
  8. md5(Object content)
  9. md5(Path path)