實現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);  
    }
}git

相關文章
相關標籤/搜索