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

namespace WS
{
    /// <summary>MD5加密</summary>
    public class MD5Encrypt
    {
        /// <summary>16位MD5加密</summary>
        public static string Encrypt16(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            using (var md5 = MD5.Create())
            {
                byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                return buffer.ToHex();
            }
        }

        /// <summary>32位MD5加密</summary>
        public static string Encrypt32(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            using (var md5 = MD5.Create())
            {
                string pwd = string.Empty;
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                foreach (var item in s)
                {
                    pwd = string.Concat(pwd, item.ToString("X"));
                }
                return pwd;
            }
        }

        /// <summary>64位MD5加密</summary>
        public static string Encrypt64(string str)
        {
            if (string.IsNullOrEmpty(str))
                return null;

            using (var md5 = MD5.Create())
            {
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                return s.ToBase64();
            }
        }

        /// <summary>MD5加密</summary>
        /// <param name="sourceString">值</param>
        /// <param name="isletter">是否小写</param>
        public static string GetMD5(string sourceString, bool isletter = false)
        {
            if (string.IsNullOrEmpty(sourceString)) return null;
            MD5 md5 = MD5.Create();
            byte[] source = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < source.Length; i++)
            {
                if (!isletter)
                    sBuilder.Append(source[i].ToString("X2"));
                else
                    sBuilder.Append(source[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }
}

