MD5.java 1.84 KB
package cn.com.glsx.entmicro.util;

import java.security.MessageDigest;

/**
 * @author zhouhaibao
 * @version 1.0
 * @description: TODO
 * @date 2021/11/23 21:39
 */
public class MD5 {
    /**
     * 32位MD5加密算法
     * @param bytes
     * @return
     */
    public static String convert32(String s){
        char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] bytes = s.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        }
        catch (Exception e){
            return null;
        }
    }

    /**
     * 16位MD5加密算法
     * @param bytes
     * @return
     */
    public static String convert16(String s){
        char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] bytes = s.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars).substring(8, 24);
        }
        catch (Exception e){
            return null;
        }
    }
}