MD5工具类

package com.lz.crowdfunding.util;

import java.security.MessageDigest;

/**
 * @ClassName MD5Util
 * @Description: TODO
 * @Author MAlone
 * @Date 2020/2/2
 * @Version V1.0
 **/
public class MD5Util {
    public static String digest16(String inStr) {
        return digest(inStr, 16);
    }
    public static String digest(String inStr) {
        return digest(inStr, 32);
    }
    private static String digest(String inStr, int rang) {
        MessageDigest md5 = null;
        if ( StringUtil.isEmpty(inStr) ) {
            return "";
        }

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuilder hexValue = new StringBuilder();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        if ( rang == 32 ) {
            return hexValue.toString();
        } else {
            return hexValue.toString().substring(8, 24);
        }
    }

    public static void main(String args[]) {
        String s = new String("1");
        // 加密
        System.out.println(digest(s));
    }
}

MD5工具类MD5工具类 YanLzh_MAlone 发布了36 篇原创文章 · 获赞 0 · 访问量 380 私信 关注
上一篇:angluar框架面试题


下一篇:python+requests——http digest auth摘要式身份认证