這是我以前做的壹個小項目時用到md5寫的
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//將用戶密碼進行md5加密 並返回加密後的32位十六進制密碼
public class MD5Util {
public static String md5(String password) {
try {
// 獲取md5對象
MessageDigest md = MessageDigest.getInstance("md5");
// 獲取加密後的密碼並返回十進制字節數組
byte[] bytes = md.digest(password.getBytes());
// 遍歷數組得到每個十進制數並轉換成十六進制
StringBuffer sb = new StringBuffer();
for (byte b : bytes) {
// 把每個數轉成十六進制 存進字符中
sb.append(toHex(b));
}
String finish = sb.toString();
return finish;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
// 十進制轉十六進制方法
private static String toHex(byte b) {
int target = 0;
if (b < 0) {
target = 255 + b;
} else {
target = b;
}
int first = target / 16;
int second = target % 16;
return Hex[first] + Hex[second];
}
static String[] Hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f" };
/*public static void main(String[] args) {
String a = MD5Util.md5("1234");
System.out.println(a);
}*/
}