Java SHA256 sha256Digest(final InputStream data)

Here you can find the source of sha256Digest(final InputStream data)

Description

sha Digest

License

Apache License

Declaration

public static byte[] sha256Digest(final InputStream data) throws NoSuchAlgorithmException, IOException 

Method Source Code


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

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final int STREAM_BUFFER_LENGTH = 1024;

    public static byte[] sha256Digest(final InputStream data) throws NoSuchAlgorithmException, IOException {
        MessageDigest digest = getSHA256MessageDigest();
        updateMessageDigest(digest, data);
        return digest.digest();
    }/*from  w  w w  .ja  v  a 2  s . com*/

    public static byte[] sha256Digest(final byte[] data) throws NoSuchAlgorithmException {
        return getSHA256MessageDigest().digest(data);
    }

    public static byte[] sha256Digest(final String data, final Charset charset) throws NoSuchAlgorithmException {
        return getSHA256MessageDigest().digest(data.getBytes(charset));
    }

    public static MessageDigest getSHA256MessageDigest() throws NoSuchAlgorithmException {
        return getMessageDigest("SHA-256");
    }

    private static void updateMessageDigest(MessageDigest digest, final InputStream data) throws IOException {
        final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
        int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

        while (read > -1) {
            digest.update(buffer, 0, read);
            read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
        }
    }

    public static MessageDigest getMessageDigest(final String algorithm) throws NoSuchAlgorithmException {
        return MessageDigest.getInstance(algorithm);
    }
}

Related

  1. SHA256(String texto)
  2. SHA256Binary(String toHash)
  3. SHA256byte(String input)
  4. sha256digest(@Nonnull byte[] data)
  5. sha256Digest(byte[] bytes)
  6. sha256Encode(String message)
  7. sha256encrypt(String phrase)
  8. sha256Hash()
  9. sha256Hash(byte[] data)