MD5工具类

作者: Small_Cake | 来源:发表于2017-08-17 10:42 被阅读190次
    package com.smallcake.utils;
    
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    /**
     * MD5 Utils
     */
    
    public class MD5Utils {
        // 全局数组
        private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    
        public static String encrypt32(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 String encrypt32Up(String strObj){
            return encrypt32(strObj).toUpperCase();
        }
        public static String encrypt16(String strObj){
            return encrypt32(strObj).substring(8,24);
        }
        public static String encrypt16Up(String strObj){
            return encrypt32Up(strObj).substring(8,24);
        }
    
    
    
    
        // 转换字节数组为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();
        }
        // 返回形式为数字跟字符串
        private static String byteToArrayString(byte bByte) {
            int iRet = bByte;
            if (iRet < 0) {
                iRet += 256;
            }
            int iD1 = iRet / 16;
            int iD2 = iRet % 16;
            return strDigits[iD1] + strDigits[iD2];
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:MD5工具类

        本文链接:https://www.haomeiwen.com/subject/cqygrxtx.html