Java: How to create SHA-1 for a file?

Witek picture Witek · Jun 9, 2011 · Viewed 24.1k times · Source

What is the best way to create a SHA-1 for a very large file in pure Java6? How to implement this method:

public abstract String createSha1(java.io.File file);

Answer

Jeff Foster picture Jeff Foster · Jun 9, 2011

Use the MessageDigest class and supply data piece by piece. The example below ignores details like turning byte[] into string and closing the file, but should give you the general idea.

public byte[] createSha1(File file) throws Exception  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    InputStream fis = new FileInputStream(file);
    int n = 0;
    byte[] buffer = new byte[8192];
    while (n != -1) {
        n = fis.read(buffer);
        if (n > 0) {
            digest.update(buffer, 0, n);
        }
    }
    return digest.digest();
}