Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); 
like image 267
Witek Avatar asked Jun 09 '11 13:06

Witek


People also ask

What is SHA-1 in Java?

SHA-1 or Secure Hash Algorithm 1 is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value. This hash value is known as a message digest. This message digest is usually then rendered as a hexadecimal number which is 40 digits long.

What is a SHA-1 file?

File containing a "block" used by a SHA-1 block cipher cryptographic algorithm; typically stores a series of bits, or characters, that are used for verifying an identity when run through the SHA-1 hash function. When hosting a file for download, sometimes a developer will also provide a ".


1 Answers

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(); } 
like image 184
Jeff Foster Avatar answered Sep 20 '22 04:09

Jeff Foster