How To Generate SHA1 Hash Value Of File

5 years ago by in How To, Utilities Tagged: , , , , , ,

Using the MessageDigest class, we can generate the SHA-1 hash value of a file as shown below.

  public static String sha1(final File file) throws NoSuchAlgorithmException, IOException {
    final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");

    try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
      final byte[] buffer = new byte[1024];
      for (int read = 0; (read = != -1;) {
        messageDigest.update(buffer, 0, read);

    // Convert the byte to hex format
    try (Formatter formatter = new Formatter()) {
      for (final byte b : messageDigest.digest()) {
        formatter.format("%02x", b);
      return formatter.toString();

Note that a similar technique can be applied to generate the SHA-1 value of any stream.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.