/***
* MD5 class
* Computes MD5-Hashes out of Input-Strings
* Author: Christoph Mauerhofer, http://christophmauerhofer.com/
* Date: 2010/11/13
***/

import java.lang.*;
import java.security.*;


class MD5
{
  // Members
  private String inputStr = new String();
  
  // Constructor
  MD5() {
    inputStr = "";
  }
  
  MD5(String inputStr) {
    this.inputStr = inputStr;
  }
  
  public void setData(String inputStr) {
    this.inputStr = inputStr;
  }
  
  public String getData() {
    return inputStr;
  }
  
  private byte[] digest() {
    byte[] result;
    
    try {
      // Computation
      MessageDigest digest = MessageDigest.getInstance("MD5");  // creates MessageDigest-object for md5 algorithm
      digest.reset();
      digest.update(inputStr.getBytes());  // updates source for digest
      result = digest.digest();  // computes and saves hash
    }
    catch(NoSuchAlgorithmException exception) {
      System.out.println("ERROR: NoSuchAlgorithmExcpetion");
      result = new byte[1];
    }
    
    return result;
  }
  
  public String getChecksum() {
    StringBuffer hexStr = new StringBuffer();
    byte[] result = digest();
    
    for (int i=0; i<result.length; i++) {
      if (result[i] >= 0 && result[i] <= 15) {  // hex number has only one digit (leading digit is zero)
        hexStr.append("0");  // add "0" as first digit of the two-digit-hex-number (one byte)
      }
      hexStr.append(Integer.toHexString(0xFF & result[i]));
    }
    
    return hexStr.toString();
  }
  
}


