Using a DigestOutputStream

With a DigestOutputStream, you can calculate a digest (SHA, MD5) while you are passing data through the stream. The process of calculating the digest can be turned off and on with the method DigestOutputStream.on(boolean).

In the following example, Main.java is read in and written to Main.java.digest. In the process, every other byte is taken into account to update the digest. In the end, the digest is appended to Main.java.digest.

Main.java:

import java.security.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      try {
         FileInputStream fis = new FileInputStream("Main.java");
         FileOutputStream fos = new FileOutputStream("Main.java.digest");
 
         MessageDigest md = MessageDigest.getInstance("SHA");
         DigestOutputStream dos = new DigestOutputStream(fos, md);
 
         int b;
         boolean state = true;
         while ((b = fis.read()) != -1) {
            dos.write(b);
 
            state = !state;
            dos.on(state);
         }
 
         // turn of digest calculation
         // and write digest to end of file
         dos.on(false);
         byte[] buffer = md.digest();
         dos.write(buffer, 0, buffer.length);
         dos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}