简单MD5加密工具-UTF-8

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 简单MD5加密工具
 * @author Jack
 */
public class MD5Util {
    public static String hexMD5(String string) {
        String md5 = MD5(string);
        if (null != md5 && md5.length() >= 24)
            md5 = md5.substring(8, 24);
        return md5;
    }

    public static String MD5(String string) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return byteArrayToHexString(md.digest(string.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            return null;
        }
    }

    public static String MD5(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return byteArrayToHexString(md.digest(bytes));
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 0xFF) < 16)
                buf.append("0");
            buf.append(Long.toString((bytes[i] & 0xFF), 16));
        }
        return buf.toString();
    }

    /**
     * 返回当前日期年月日时分秒
     * @return
     */
    private static String getCurrentDate() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        return currentTime;
    }

    public static void main(String[] args) {
        String module = "ptsOperanDayFeignApi.staicsList";//模块
        String account = "G111209";//专属账号
        String pwd = "C22711113514";//专属密码
        String signKey= "84911111111KKJ816";//密钥
        String currentDate = getCurrentDate();
        StringBuilder sb = new StringBuilder(module).append(account).append(signKey).append(pwd).append(currentDate);
        String reuslt = MD5((sb.toString())).toUpperCase();
        System.out.println("加密前参数:");
        System.out.println("module:" + module);
        System.out.println("account:" + account);
        System.out.println("signKey:" + signKey);
        System.out.println("pwd:" + pwd);
        System.out.println("currentDate:" + currentDate +" 格式:yyyyMMddHHmmss");
        System.out.println("------------------------------------");
        System.out.println("参数组合:" + sb.toString());
        System.out.println("------------------------------------");
        System.out.println("加密结果");
        System.out.println("32位大写:" + reuslt);
        System.out.println("16位大写:" + reuslt.substring(8, 24));

    }
}

 

posted @ 2022-09-28 16:07  敲代码的机车Boy  阅读(456)  评论(0编辑  收藏  举报