Generating a SHA or SHA-1 message digest

Instantiate a MessageDigest object with the static method getInstance(“SHA”) or getInstance(“SHA-1″). Use the method update to pass in an array of bytes on which you want to compute a hash (you can call this method several times successively). After having passed in all the input bytes, get the digest by calling digest. The result is a 20 byte digest. You don’t need to reinstantiate a MessageDigest object if you need to compute digests of several byte streams, use the method reset to empty the buffer.

Main.java:

import java.security.*;
import java.io.*;
 
public class Main 
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0]));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int c;
      while ((c = bis.read()) > -1) {
         baos.write(c);
      }
      bis.close();
      byte[] buf = baos.toByteArray();
 
      System.out.println(buf);
 
      MessageDigest md = MessageDigest.getInstance("SHA");
      md.update(buf);
      byte[] digest = md.digest();
 
      System.out.println("Digest (byte values):");
      for (int i=0; i<digest.length; i++) {
         System.out.print(digest[i] + " ");
      }
   }
}