Java Digest digest(InputStream input, String algorithm)

Here you can find the source of digest(InputStream input, String algorithm)

Description

digest

License

Apache License

Declaration

public static String digest(InputStream input, String algorithm) throws IOException, NoSuchAlgorithmException 

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 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) {
                ;//from www  . j a  v a 2  s .c  o  m
            }
            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. digest(final byte[] data)
  2. digest(final InputStream inputStream, final MessageDigest digester)
  3. digest(final java.security.MessageDigest messageDigest, final java.nio.ByteBuffer data)
  4. digest(final String algorithm, final byte[] bytes)
  5. digest(final String password)
  6. digest(InputStream is, String digestAlgorithm)
  7. digest(MessageDigest digest, InputStream data)
  8. digest(MessageDigest method, File f)
  9. digest(Serializable object)