那些年java MD5加密字符编码的坑

相信做过MD5加密的童鞋都遇到过字符编码的坑,一般加密出来的结果和其他人不一样都是字符编码不一致导致的,比如类文件的字符编码、浏览器的字符编码等和对方不一致,所以就需要转码统一字符。

以下是笔者转码过程中遇到的坑:

不要new String("XXXX".getBytes("UTF-8")),之后将转码后的字串传入MD5去加密,会遇到意想不到的效果,有的字符加密出来和对方一样,有的不一样,特提供以下两个方法,供参考:

方法一:

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();  
    }  

方法二:

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";
        }
    }

注意代码中的  “

digest

原文地址:https://www.cnblogs.com/xxlu/p/8066513.html