package cn.axzo.workflow.starter.util;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Starter 专用的 MD5小工具
 *
 * @author wangli
 * @since 2025-03-05 16:45
 */
public class MD5 {

    public static String encrypt(String data) {
        if (data == null) {
            return null;
        }
        try {
            // 获取 MD5 算法实例
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将输入字符串转换为字节数组并进行加密
            byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为 BigInteger
            BigInteger bigInt = new BigInteger(1, digest);
            // 将 BigInteger 转换为十六进制字符串
            String hashText = bigInt.toString(16);
            // 不足 32 位时前面补 0
            while (hashText.length() < 32) {
                hashText = "0" + hashText;
            }
            return hashText;
        } catch (NoSuchAlgorithmException e) {
            // 处理算法不可用的异常
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String encrypt = encrypt("123");
        System.out.println("encrypt = " + encrypt);
    }
}
