Java Hash Calculate getHash(byte[] bytes)

Here you can find the source of getHash(byte[] bytes)

Description

get Hash

License

Open Source License

Declaration

public static byte[] getHash(byte[] bytes) throws IOException 

Method Source Code


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

import java.io.*;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final int BUFFER_SIZE = 1 << 14;

    public static byte[] getHash(Path path) throws IOException {
        try (InputStream input = new FileInputStream(path.toFile())) {
            return getHash(input);
        }//from   w  ww . j  a  va2 s .  c o  m
    }

    public static byte[] getHash(byte[] bytes) throws IOException {
        return getHash(bytes, 0, bytes.length);
    }

    public static byte[] getHash(byte[] bytes, int offset, int len) throws IOException {
        try (InputStream input = new ByteArrayInputStream(bytes, offset, len)) {
            return getHash(input);
        }
    }

    public static byte[] getHash(InputStream inputStream) throws IOException {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA1");
            return createHash(inputStream, digest);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Could not create hash due digest initialization error", e);
        }
    }

    private static byte[] createHash(InputStream inputStream, MessageDigest digest) throws IOException {
        byte[] buf = new byte[BUFFER_SIZE];
        int read;
        while ((read = inputStream.read(buf)) > 0) {
            digest.update(buf, 0, read);
        }
        return digest.digest();
    }
}

Related

  1. calculateHash(int x, int y)
  2. calculateHash(Long... ids)
  3. calculateHash(String str)
  4. calculateHashCode(byte a[])
  5. getHash(byte[] bytes)
  6. getHash(byte[] data)
  7. getHash(byte[] data)
  8. getHash(byte[] data, int offset, int length)
  9. getHash(byte[] inputBytes)