Digest Stream : MessageDigest « Security « Java Tutorial






import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;

public class MainClass {
  public static void main(String[] args) throws Exception{
    performOutputTest();
    performInputTest();
  }

  static void performOutputTest() throws Exception {
      MessageDigest md = MessageDigest.getInstance("SHA");
      FileOutputStream fout = new FileOutputStream("sha-results.txt");
      DigestOutputStream out = new DigestOutputStream(fout, md);
      byte[] b = "testCase".getBytes();
      out.write(b, 0, b.length);
      md = out.getMessageDigest();
      String s = new String(md.digest());
      System.out.println("Calculated result: " + s);
  }

  static void performInputTest()  throws Exception{
      MessageDigest md = MessageDigest.getInstance("SHA");
      FileInputStream fin = new FileInputStream("sha-results.txt");
      DigestInputStream in = new DigestInputStream(fin, md);
      byte[] b = new byte["testCase".getBytes().length];
      in.read(b, 0, "testCase".getBytes().length);
      md = in.getMessageDigest();
      String s = new String(md.digest());
      System.out.println("Calculated result:  " + s);
  }
}








36.27.MessageDigest
36.27.1.Message Digest Demo
36.27.2.Digest Stream
36.27.3.Make SHA Message
36.27.4.Make SHA Message with update methods
36.27.5.Masher a file
36.27.6.extends MessageDigest
36.27.7.MD5 MessageDigest
36.27.8.Digest Input
36.27.9.Create an encrypted string for password
36.27.10.Cryptography Streams: URLDigest