public static String createHash(String value) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(value.getBytes("UTF-8"));
byte[] byteValues = md.digest();
byte singleChar = 0;
if (byteValues == null || byteValues.length <= 0) return null;
String entries[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
StringBuffer out = new StringBuffer(byteValues.length * 2);
for (int i = 0; i < byteValues.length; i++) {
singleChar = (byte) (byteValues[i] & 0xF0);
singleChar = (byte) (singleChar >>> 4);
singleChar = (byte) (singleChar & 0x0F);
out.append(entries[(int) singleChar]);
singleChar = (byte) (byteValues[i] & 0x0F);
out.append(entries[(int) singleChar]);
}
String rslt = new String(out);
return rslt;
}
catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; }
catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; }
}
public final class MD5Encoder {
private static final char[] hexadecimal =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Encodes the 128 bit (16 bytes) MD5 into a 32 character String.
*
* @param binaryData Array containing the digest
* @return Encoded MD5, or null if encoding failed
*/
public String encode( byte[] binaryData ) {
if (binaryData.length != 16)
return null;
char[] buffer = new char[32];
for (int i=0; i<16; i++) {
int low = (int) (binaryData[i] & 0x0f);
int high = (int) ((binaryData[i] & 0xf0) >> 4);
buffer[i*2] = hexadecimal[high];
buffer[i*2 + 1] = hexadecimal[low];
}
return new String(buffer);
}
}