
Originariamente inviata da
andbin
Il "minimo" per fare la cosa corretta e un pochino pulita (ma si potrebbe fare ancora meglio!) può essere questo, scritto e provato al volo:
codice:
public class DigestUtils {
private DigestUtils() {}
public static String md5Hex(String str) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(utf8Bytes(str));
BigInteger number = new BigInteger(1, digest);
return String.format("%032x", number);
}
private static byte[] utf8Bytes(String str) {
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error("Grave error, UTF-8 not supported!");
}
}
}