0

I am studying MD5 and also SHA with MessageDigest. Here is a code I have from class that implements MD5 with MessageDigest. I am having trouble understanding it.

So it gets the "instance" of MD5. I guess that is the MD5 algorithm? Then it updates the bytes. Why does it do this? Then it creates a variable bytes b with md.digest(), but I am not sure why it does this either? Then I think it uses the for statement to do the algorithm and maybe pad it (append 0?). If anyone could explain a little better, I'd appreciate!

   try {
                MessageDigest md = MessageDigest.getInstance("MD5"); // get the
                                                                        // instance
                                                                        // of md5
            md.update(bytes); // get the digest updated
            byte[] b = md.digest(); // calculate the final value
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            message = buf.toString(); // output as strings

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace(); // when certain algorithm is down, output the
                                    // abnormal condition
        }
        return message;
    }
RockOn
  • 197
  • 1
  • 19

1 Answers1

2

md.update(bytes) just puts the bytes through MD5. byte[] b = md.digest() gets out the result of the MD5 hash as a series of bytes.

Then the whole rest of the code is a dreadfully awkward way to convert bytes into a hexadecimal string.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413