How do you create a Message Digest with the Java Security API? (Message Digest code example)

Lennart Jorelid

A:  A simple example of creating and using the MessageDigest class. Note that the factory method getInstance is the only way to create a MessageDigest object. After calling the digest method, the Message Digest object is reset to its original state.

Code example
public static void main(String[] args) throws Exception
  {
      // Create a Message Digest from a Factory method
      MessageDigest md = MessageDigest.getInstance("SHA-1");

      // Create the message
      String orig = "And now for something completely different... the larch.";
      byte[] msg = orig.getBytes();

      // Update the message digest with some more bytes
      // This can be performed multiple times before creating the hash
      md.update(msg);

      // Create the digest from the message
      byte[] aMessageDigest = md.digest();

      // Printout
      System.out.println("Original: " + new String(msg));
      System.out.println("Message Digest: " + new String(aMessageDigest));
  }
Resulting output
Original: And now for something completely different... the larch.
Message Digest: ♦═7→ ╚B╩b╩l
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact