using System.Security.Cryptography;
using System.Text;

namespace NPin.Framework.Core.Crypt;

public static class Md5Extensions
{
    /// <summary>
    /// 获取16位长度的MD5大写字符串
    /// 截取第 9~25 位
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string To16Md5(this string value) => value.Md5().Substring(8, 16);

    /// <summary>
    /// 获取32位长度的MD5大写字符串
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string Md5(this string value)
    {
        using var md5 = MD5.Create();

        var inputBytes = Encoding.UTF8.GetBytes(value);
        var hashBytes = md5.ComputeHash(inputBytes);

        var sb = new StringBuilder();
        foreach (var hash in hashBytes)
        {
            sb.Append(hash.ToString("X2"));
        }

        return sb.ToString();
    }
}