工具篇——MD5Util(加密字符串)

写代码的四点:
     1.明确需求。要做什么?
     2.分析思路。要怎么做?(1,2,3……)
     3.确定步骤。每一个思路要用到哪些语句、方法和对象。
     4.代码实现。用具体的语言代码将思路实现出来。

学习新技术的四点:
     1.该技术是什么?
     2.该技术有什么特点?(使用需注意的方面)
     3.该技术怎么使用?(写Demo)
     4.该技术什么时候用?(在Project中的使用场景 )

----------------------早计划,早准备,早完成。-------------------------

package com.gzqol.hb.mendianguanli.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 1.MD5加密字符串(32位大写)
 * 2.MD5加密字符串(32位小写)
 * <p>
 * MD5在线加密:https://md5jiami.51240.com/
 */

public class MD5Util {

    /**
     * MD5加密字符串(32位大写)
     *
     * @param string 需要进行MD5加密的字符串
     * @return 加密后的字符串(大写)
     */
    public static String md5Encrypt32Upper(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

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

    /**
     * MD5加密字符串(32位小写)
     *
     * @param string 需要进行MD5加密的字符串
     * @return 加密后的字符串(小写)
     */
    public static String md5Encrypt32Lower(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

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

    /**
     * Unicode中文编码转换成字符串
     *
     * @param str
     * @return
     */
    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }
}

猜你喜欢

转载自blog.csdn.net/qq941263013/article/details/80081127