JAVA中的MD5加密
在java.security包中實行Java內部的MD5加密
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class MD5 {
public static String encrypt(String strSrc) {
try {
// 16進制的所有字符數組
char hexChars[] = { '0', '1', '2', '3',
'4', '5', '6', '7', '8','9', 'a', 'b', 'c',
'd', 'e', 'f' };
// 輸入的字符串轉換成字節數組
byte[] bytes = strSrc.getBytes();
// 拿到一個MD5轉換器(如果想要SHA1參數換成”SHA1”)
MessageDigest md = MessageDigest.getInstance("MD5");
// bytes是輸入字符串轉換得到的字節數組,使用指定字節更新摘要
md.update(bytes);
// 轉換並返回結果,也是字節數組,包含16個元素
bytes = md.digest();
// 取出字節數組的長度
int j = bytes.length;
// 並創建一個字符數組,容量是其2倍 32
char[] chars = new char[j * 2];
// 定義一個數組的下標記錄數
int k = 0;
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
// 將每個數b進行雙字節加密
// 不帶符號右移4位,移位處補0 & 十六進制的f 即 高四位清空 取低四位的值
chars[k++] = hexChars[b >>> 4 & 0xf];
chars[k++] = hexChars[b & 0xf];
}
// 返回加密後的字符串
return new String(chars);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("MD5加密出錯!!+" + e);
}
}
public static void main(String[] args) {
System.out.println(MD5.encrypt("111111"));
}
}