Created
April 14, 2010 04:08
-
-
Save ananthakumaran/365438 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
public class HashService { | |
public static char[] HEX_CHARS = new char[] { | |
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', | |
'E', 'F'}; | |
/** | |
* Computes the MD5 hash for the specified byte array. | |
* | |
* @return a big fat string encoding of the MD5 for the content, suitably | |
* formatted for use as a file name | |
*/ | |
public static String getMD5Hash(byte[] content) { | |
MessageDigest md5; | |
try { | |
md5 = MessageDigest.getInstance("MD5"); | |
} catch (NoSuchAlgorithmException e) { | |
throw new RuntimeException("Error initializing MD5", e); | |
} | |
md5.update(content); | |
return toHexString(md5.digest()); | |
} | |
/** | |
* Returns a string representation of the byte array as a series of | |
* hexadecimal characters. | |
* | |
* @param bytes byte array to convert | |
* @return a string representation of the byte array as a series of | |
* hexadecimal characters | |
*/ | |
public static String toHexString(byte[] bytes) { | |
char[] hexString = new char[2 * bytes.length]; | |
int j = 0; | |
for (int i = 0; i < bytes.length; i++) { | |
hexString[j++] = HEX_CHARS[(bytes[i] & 0xF0) >> 4]; | |
hexString[j++] = HEX_CHARS[bytes[i] & 0x0F]; | |
} | |
return new String(hexString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment