java完成MD5加密辦法匯總。本站提示廣大學習愛好者:(java完成MD5加密辦法匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成MD5加密辦法匯總正文
代碼一:
/**
* 完成MD5加密
*
*/
public class MD5 {
/**
* 獲得加密後的字符串
* @param input
* @return
*/
public static String stringMD5(String pw) {
try {
// 拿到一個MD5轉換器(假如想要SHA1參數換成”SHA1”)
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
// 輸出的字符串轉換成字節數組
byte[] inputByteArray = pw.getBytes();
// inputByteArray是輸出字符串轉換獲得的字節數組
messageDigest.update(inputByteArray);
// 轉換並前往成果,也是字節數組,包括16個元素
byte[] resultByteArray = messageDigest.digest();
// 字符數組轉換成字符串前往
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String byteArrayToHex(byte[] byteArray) {
// 起首初始化一個字符數組,用來寄存每一個16進制字符
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
// new一個字符數組,這個就是用來構成成果字符串的(說明一下:一個byte是八位二進制,也就是2位十六進制字符(2的8次方等於16的2次方))
char[] resultCharArray =new char[byteArray.length * 2];
// 遍歷字節數組,經由過程位運算(位運算效力高),轉換成字符放到字符數組中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b& 0xf];
}
// 字符數組組分解字符串前往
return new String(resultCharArray);
}
}
辦法二:
package other;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
* MD5 算法
*/
public class MD5 {
// 全局數組
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public MD5() {
}
// 前往情勢為數字跟字符串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
// 前往情勢只為數字
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
// 轉換字節數組為16進制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
public static String GetMD5Code(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 該函數前往值為寄存哈希值成果的byte數組
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
public static void main(String[] args) {
MD5 getMD5 = new MD5();
System.out.println(getMD5.GetMD5Code("000000"));
}
}