-1

I've found this java function that encrypt a string in MD5, but I fail to understand how it works:

public static String makeMD5(String text){
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");

        md.update(text.getBytes());
        byte byteData[] = md.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++)
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));

        text = sb.toString();
        return text;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

I don't understand the line just after the for loop..

Thanks a lot!

DevMan91
  • 107
  • 5

1 Answers1

0

The line after the for loop is a frankly overcomplicated way to convert a byte array into hexadecimal. An equivalent, simpler approach might be

sb.append(String.format("%02x", b & 0xff));

though if you can use third-party libraries there are even simpler solutions. How to convert a byte array to a hex string in Java? has a number of suggestions.

(If third party libraries are available, Guava will let you do this whole method in the one line Hashing.md5().hashString(text, Charset.defaultCharset()).toString().)

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