How do I work with message digests?

John Zukowski

  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();
    
  6. Save or print digest bytes. If you happen to use Integer.toHexString(), remember that this doesn't print leading zeros.
    StringBuffer hexString = new StringBuffer();
    for (int i=0;i<digest.length;i++) {
      hexString.append(
        Integer.toHexString(0xFF & digest[i]));
      hexString.append(" ");
    }
    System.out.println(hextString.toString());
    
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


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

 

 

About | Sitemap | Contact