Question How do I work with message digests?
Topics Java:API:Security
Author John Zukowski
Created Dec 31, 1999 Modified Feb 21, 2000

Answer
  1. Get the message content as a byte[]. If coming from a file, read bytes from FileInputStream into ByteArrayOutputStream. Other sources would use similar methods, but remember to not treat content as characters.
    FileInputStream fis = 
      new FileInputStream(filename);
    BufferedInputStream bis = 
      new BufferedInputStream(fis);
    ByteArrayOutputStream baos = 
      new ByteArrayOutputStream();
    int ch;
    while ((ch = bis.read()) != -1) {
      baos.write(ch);
    }
    byte[] buffer = baos.toByteArray();
    
  2. Get a MessageDigest for the appropriate algorithm. The JDK provides implementations of SHA-1 (or SHA, from NIST FIPS 180-1) and MD5 (from MIT, algorithm RSA-MD5, as defined by RSA DSI in RFC 1321). If you request an algorithm where no provider is available, NoSuchAlgorithmException is thrown. The SHA algorithm results in a 20-byte digest, while MD5 is 16 bytes long.
    MessageDigest algorithm = 
      MessageDigest.getInstance("SHA-1");
    

    or

    MessageDigest algorithm = 
      MessageDigest.getInstance("MD5");
    
  3. Ensure the digest's buffer is empty. This isn't necessary the first time used. However, it is good practice to always empty the buffer out in case you later reuse it.
    algorithm.reset();
    
  4. Fill the digest's buffer with data to compute a message digest from.
    algorithm.update(buffer);
    
    
  5. Generate the digest. This does any necessary padding required by the algorithm.
    byte[] digest = algorithm.digest();