Java SHA256 sha256(final InputStream inputStream)

Here you can find the source of sha256(final InputStream inputStream)

Description

Calculate the SHA-256 hash over the bytes read from the given input stream

License

Open Source License

Parameter

Parameter Description
inputStream The input stream

Exception

Parameter Description
IOExceptionWhen there occurred an error while reading from the givenInputStream
IllegalArgumentException When the given InputStream is 'null'

Return

The 32 byte long SHA-256 hash as a byte array

Declaration

public static byte[] sha256(final InputStream inputStream) throws IOException, IllegalArgumentException 

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;
import java.util.Objects;

public class Main {
    /**//  w  ww . j  a v  a  2  s .c  om
     * The default buffer size, used while reading data from an input stream
     */
    private static final int BUFFER_SIZE = 1024 * 1024;

    /**
     * Calculate the SHA-256 hash over the bytes read from the given input stream
     *
     * @param inputStream The input stream
     * @return The 32 byte long SHA-256 hash as a byte array
     * @throws IOException              When there occurred an error while reading from the given
     *                                  {@link InputStream}
     * @throws IllegalArgumentException When the given {@link InputStream} is 'null'
     */
    public static byte[] sha256(final InputStream inputStream) throws IOException, IllegalArgumentException {
        Objects.requireNonNull(inputStream);

        try {
            final byte[] buffer = new byte[BUFFER_SIZE];
            final MessageDigest digest = MessageDigest.getInstance("SHA-256");

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, bytesRead);
            }

            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("SHA-256 hashing algorithm unknown in this VM.", e);
        }
    }
}

Related

  1. sha256(byte[] data)
  2. SHA256(byte[] input)
  3. SHA256(byte[] P)
  4. SHA256(byte[] src)
  5. SHA256(ByteBuffer buf, int off, int length)
  6. sha256(final String string)
  7. sha256(InputStream data)
  8. sha256(String base)
  9. sha256(String base)