当前位置:网站首页>MD5 tool class

MD5 tool class

2022-07-04 22:30:00 wgq18586361686

package com.example.springboottemplate.util;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 Encryption utility class 
 */
public class MD5Util {
    private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * MD5 encryption  ( Capitalization )
     *
     * @param inStr
     * @return 32byte MD5 Value
     */
    public static String MD5(String inStr) {
        byte[] inStrBytes = inStr.getBytes();
        try {
            MessageDigest MD = MessageDigest.getInstance("MD5");
            MD.update(inStrBytes);
            byte[] mdByte = MD.digest();
            char[] str = new char[mdByte.length * 2];
            int k = 0;
            for (int i = 0; i < mdByte.length; i++) {
                byte temp = mdByte[i];
                str[k++] = hexDigits[temp >>> 4 & 0xf];
                str[k++] = hexDigits[temp & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * MD5 encryption ( A lowercase letter )
     *
     * @param source
     * @return
     */
    public static String md5(String source) {

        StringBuffer sb = new StringBuffer(32);
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes("utf-8"));
            for (int i = 0; i < array.length; i++) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String str ="123";
        System.out.println(MD5Util.MD5(str));
        System.out.println(MD5Util.md5(str));
    }
}

原网站

版权声明
本文为[wgq18586361686]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042200283036.html