Java SHA1 sha1(File sourceFile)

Here you can find the source of sha1(File sourceFile)

Description

Computes the hash of a file or directory.

License

Open Source License

Parameter

Parameter Description
sourceFile the original file or directory

Exception

Parameter Description
Exception if any IOException of SecurityException occured

Return

an hex string representing the SHA1 hash of the file or directory.

Declaration

public static String sha1(File sourceFile) throws Exception 

Method Source Code


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

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.security.MessageDigest;

public class Main {
    /**//from  w  w  w.  j  av a 2 s  . com
     * Computes the hash of a file or directory.
     *
     * @param sourceFile the original file or directory
     * @return an hex string representing the SHA1 hash of the file or directory.
     * @throws Exception if any IOException of SecurityException occured
     */
    public static String sha1(File sourceFile) throws Exception {
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("SHA-1");
        updateDigest(complete, sourceFile, buffer);
        byte[] bytes = complete.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    private static void updateDigest(final MessageDigest digest, final File sourceFile, final byte[] buffer)
            throws IOException {
        if (sourceFile.isFile()) {
            try (InputStream fis = new FileInputStream(sourceFile)) {
                int numRead;
                do {
                    numRead = fis.read(buffer);
                    if (numRead > 0) {
                        digest.update(buffer, 0, numRead);
                    }
                } while (numRead != -1);
            }
        } else if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            if (files != null) {
                for (File file : files) {
                    updateDigest(digest, file, buffer);
                }
            }
        }
    }
}

Related

  1. SHA1(byte[] src)
  2. SHA1(ByteBuffer buf, int offset, int size)
  3. sha1(File f)
  4. sha1(File file)
  5. sha1(File file)
  6. sha1(final byte[] bytes)
  7. sha1(final File file)
  8. sha1(final String data)
  9. sha1(final String str)