Skip to content

Instantly share code, notes, and snippets.

@fidanov
Created July 2, 2012 08:20
Show Gist options
  • Save fidanov/3031851 to your computer and use it in GitHub Desktop.
Save fidanov/3031851 to your computer and use it in GitHub Desktop.
Transform any string to MD5 hash and then to HEX representation. Useful for file names.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Util {
private static char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* Transform any string to MD5 hash and then to HEX representation.
* Very useful for using strings as file names, like when the string
* is a url or another arbitrary string.
*
* @param text
* @return
*/
public String md5(String text) {
MessageDigest hasher;
try {
hasher = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
hasher.update(text.getBytes());
byte bytes[] = hasher.digest();
char[] result = new char[bytes.length * 2];
for(int i = 0; i < bytes.length; ++i) {
result[i << 2] = hex[bytes[i] >> 4];
result[(i << 2) + 1] = hex[0x0F & bytes[i]];
}
return new String(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment