MD5 加密須要注意編碼格式!!!

相信作過MD5加密的童鞋都遇到過字符編碼的坑,通常加密出來的結果和其餘人不同都是字符編碼不一致致使的,好比類文件的字符編碼、瀏覽器的字符編碼等和對方不一致,因此就須要轉碼統一字符。git

如下是筆者轉碼過程當中遇到的坑:算法

不要new String("XXXX".getBytes("UTF-8")),以後將轉碼後的字串傳入MD5去加密,會遇到意想不到的效果,有的字符加密出來和對方同樣,有的不同,特提供如下兩個方法,供參考:瀏覽器

方法一:app

public static String MD5(String string,String enCode) {  
        byte[] hash = null;  
        try {  
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes(enCode));  
        } catch (NoSuchAlgorithmException e) {  
            logger.error("32位MD5加密出錯---->NoSuchAlgorithmException"+e.getMessage());
        } catch (UnsupportedEncodingException e) {  
            logger.error("32位MD5加密出錯---->UnsupportedEncodingException"+e.getMessage());
        }  
  
        StringBuilder hex = new StringBuilder(hash.length * 2);  
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");  
            hex.append(Integer.toHexString(b & 0xFF));
        }  
        return hex.toString();  
    }

方法二:ui

public final static String MD5(String s,String encodingType) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       

        try {
            // 按照相應編碼格式獲取byte[]
            byte[] btInput = s.getBytes(encodingType);
            // 得到MD5摘要算法的 MessageDigest 對象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字節更新摘要
            mdInst.update(btInput);
            // 得到密文
            byte[] md = mdInst.digest();
            // 把密文轉換成十六進制的字符串形式

            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;

            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return "-1";
        }
    }
相關文章
相關標籤/搜索