MD5加密本质相同,只是有不同的代码实现形式,暂时找到三种表现形式,贴出来与大家共享
第一种实现方式:
public static String md5(String str) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(str.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
第二种实现方式:
public static String md5(String string) {
if (string == null)
return null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(string.getBytes());
byte[] buffer = md.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i<buffer.length; i++) {
String s = String.format("%02x", buffer[i]);
sb.append(s);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
第三种实现方式:
private static String md5(String key) {
MessageDigest hash = null;
try {
hash = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
hash.update(key.getBytes());
byte[] digest = hash.digest();
StringBuilder builder = new StringBuilder();
for (int b : digest) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString((b >> 0) & 0xf));
}
return builder.toString();
}