摘要:
下文讲述java代码中将一个字符串转换为相应的Hash值的方法分享,如下所示;
例:
以下方法,可以将一个字符串转换为相应的Hash值
public static String strToHashKey(String k) {
String tmpKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(k.getBytes());
tmpKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
tmpKey = String.valueOf(k.hashCode());
}
return tmpKey;
}
private static String bytesToHexString(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(0xFF & b[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}