Saturday, January 29, 2011

Crypto Samples in java part one - Message Digest

Here is a simple java program illustrating how to calculate a message digest and how to verify the message digest.

import java.security.MessageDigest;

public class SimpleHashing {
 public static void main(String args[]) {
  try {

   // ----------- Calculating digest ---------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   String data = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md.update(data.getBytes());
   byte[] digest = md.digest();

   // -----------Verifying Digest -----------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md2 = MessageDigest.getInstance("SHA");

   String data2 = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md2.update(data2.getBytes());
   byte[] digestOriginal = digest;
   byte[] digestCalc = md2.digest();

   if (MessageDigest.isEqual(digestOriginal, digestCalc)) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

No comments :

Post a Comment