Description
Compute the MD-5 hash of a string, and return it has a string of hexadecimal numbers.
License
Open Source License
Parameter
Parameter | Description |
---|
text | Text to compute the MD-5 hash of |
Exception
Parameter | Description |
---|
NoSuchAlgorithmException | thrown if the MD-5 algorithm cannot be found |
UnsupportedEncodingException | thrown if the encoding is not supported |
Return
the hexadecimal representation of the hash
Declaration
public static String md5Hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException
Method Source Code
//package com.java2s;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
private static final String HASH_MD5 = "MD5";
/**/*from w ww .j a v a 2 s . c om*/
* Compute the MD-5 hash of a string, and return it has a string of hexadecimal numbers. The incoming text is assumed
* to be UTF-8 encoded. An exception will be thrown if this encoding is not supported.
*
* @param text Text to compute the MD-5 hash of
* @return the hexadecimal representation of the hash
* @throws NoSuchAlgorithmException thrown if the MD-5 algorithm cannot be found
* @throws UnsupportedEncodingException thrown if the encoding is not supported
*/
public static String md5Hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return bytesToHex(computeHash(text, HASH_MD5));
}
/**
* Convert an array of arbitrary bytes into a String of hexadecimal number-pairs with each pair representing on byte
* of the array.
*
* @param bytes the array to convert into hexadecimal string
* @return the String containing the hexadecimal representation of the array
*/
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] hexChars = new char[bytes.length << 1];
for (int i = 0; i < bytes.length; i++) {
int value = bytes[i] & 0xFF;
int baseIndex = i << 1;
hexChars[baseIndex] = hexArray[value >>> 4];
hexChars[baseIndex + 1] = hexArray[value & 0x0F];
}
return new String(hexChars);
}
private static byte[] computeHash(String text, String algorithm)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(text.getBytes("UTF-8"), 0, text.length());
return md.digest();
}
}
Related
- md5Hash(String in)
- md5Hash(String input)
- md5hash(String key)
- md5hash(String pass)
- md5Hash(String source)
- md5HashBytesToBytes(byte[] buf)
- md5HashInt(String text)