// ReSharper disable UnusedMember.Global using System.Security.Cryptography; namespace NSExt.Extensions; public static class StringExtensions { /// /// MD5 hmac编码 /// /// 字符串 /// 密钥 /// 字符串使用的编码 /// hash摘要的16进制文本形式(无连字符小写) private static string Md5Hmac(this string me, string key, Encoding e) { using var md5Hmac = new HMACMD5(e.GetBytes(key)); return BitConverter.ToString(md5Hmac.ComputeHash(e.GetBytes(me))) .Replace("-", string.Empty) .ToLower(CultureInfo.CurrentCulture); } /// /// base64编码 /// /// 待base64编码的字符串 /// 字符串的编码方式 /// 编码后的base64字符串 public static string Base64(this string me, Encoding e) { return e.GetBytes(me).Base64(); } /// /// base64解码 /// /// 待解码的字符串 /// 解码后的原始字节数组 public static byte[] Base64De(this string me) { return Convert.FromBase64String(me); } /// /// base64解码 /// /// 待解码的字符串 /// 字符串的编码方式 /// 解码后的原始字符串 public static string Base64De(this string me, Encoding e) { return e.GetString(Base64De(me)); } /// /// 将易于web传输的base64web字符串转换为原生base64 /// /// /// 原生base64 public static string Base64Sys(this string me) { return me.Replace("-", "+").Replace("_", "/").Replace(".", "="); } /// /// 将原生base64字符串转换成易于web传输的字符串 /// /// /// 易于web传输的字符串 public static string Base64Web(this string me) { return me.Replace("+", "-").Replace("/", "_").Replace("=", "."); } /// /// 将字符串转换成日期对象 /// /// 待转换字符串 /// 转换后的日期对象 public static DateTime DateTime(this string me) { return System.DateTime.Parse(me, CultureInfo.CurrentCulture); } /// /// 将字符串转换成日期对象 /// /// 待转换字符串 /// 日期格式 /// 转换后的日期对象 public static DateTime DateTimeExact(this string me, string format) { return System.DateTime.ParseExact(me, format, CultureInfo.CurrentCulture); } /// /// 将字符串转换成日期对象 /// /// 待转换字符串 /// 日期格式 /// 转换失败时返回的日期对象 /// 转换后的日期对象 public static DateTime DateTimeExactTry(this string me, string format, DateTime def) { return !System.DateTime.TryParseExact(me, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out var ret) ? def : ret; } /// /// 将字符串转换成日期对象 /// /// 待转换字符串 /// 转换失败时返回的日期对象 /// 转换后的日期对象 public static DateTime DateTimeTry(this string me, DateTime def) { return !System.DateTime.TryParse(me, out var ret) ? def : ret; } /// /// string to decimal /// /// string /// decimal public static decimal Dec(this string me) { return decimal.Parse(me, CultureInfo.CurrentCulture); } /// /// 尝试将字符串转为decimal /// /// 字符串 /// 转换失败后返回的默认值 /// 转换后的decimal public static decimal DecTry(this string me, decimal def) { return !decimal.TryParse(me, out var ret) ? def : ret; } /// /// 将字符串转换成枚举对象 /// /// /// /// public static T Enum(this string name) where T : Enum { return (T)System.Enum.Parse(typeof(T), name, true); } /// /// 将字符串转换成枚举对象 /// /// /// /// /// public static T EnumTry(this string name, T def) where T : Enum { return !System.Enum.TryParse(typeof(T), name, out var ret) ? def : (T)ret; } /// /// 将字符串转为guid /// /// 字符串 /// public static Guid Guid(this string me) { return System.Guid.Parse(me); } /// /// 将字符串转换成guid /// /// 字符串 /// 转换失败的返回值 /// public static Guid Guid(this string me, Guid def) { return System.Guid.TryParse(me, out var ret) ? ret : def; } /// /// 将字符串转换成字节数组形式 /// /// 字符串 /// 字符串使用的编码 /// 字节数组 public static byte[] Hex(this string me, Encoding e) { return e.GetBytes(me); } /// /// 将字符串转换成字节数组形式 /// /// 字符串 /// 字节数组 public static byte[] Hex(this string me) { return me.Hex(Encoding.UTF8); } /// /// 对一个字符串进行sha1 hash运算 /// /// 对一个字符串进行sha1 hash运算 /// 密钥 /// 使用的编码 /// hash摘要的16进制文本形式(无连字符小写) public static string HmacSha1(this string me, string secret, Encoding e) { using var hmacSha1 = new HMACSHA1(e.GetBytes(secret)); return BitConverter.ToString(hmacSha1.ComputeHash(e.GetBytes(me))) .Replace("-", string.Empty) .ToLower(CultureInfo.CurrentCulture); } /// /// 解码html编码 /// /// html编码后的字符串 /// 解码后的原始字符串 public static string HtmlDe(this string me) { return HttpUtility.HtmlDecode(me); } /// /// string to Int32 /// /// string /// Int32 public static int Int32(this string me) { return int.Parse(me, CultureInfo.CurrentCulture); } /// /// string to double /// /// string /// Int32 public static double Double(this string me) { return double.Parse(me, CultureInfo.CurrentCulture); } /// /// string to float /// /// string /// Int32 public static float Float(this string me) { return float.Parse(me, CultureInfo.CurrentCulture); } /// /// 尝试将字符串转为int32 /// /// 字符串 /// 转换失败后返回的默认值 /// 转换后的int32 public static int Int32Try(this string me, int def) { return !int.TryParse(me, out var ret) ? def : ret; } /// /// string to Int64 /// /// string /// Int64 public static long Int64(this string me) { return long.Parse(me, CultureInfo.CurrentCulture); } /// /// 尝试将字符串转为int64 /// /// 字符串 /// 转换失败后返回的默认值 /// 转换后的int64 public static long Int64Try(this string me, long def) { return !long.TryParse(me, out var ret) ? def : ret; } /// /// ipv4格式转int32格式 /// /// /// public static int IpV4ToInt32(this string me) { return BitConverter.ToInt32(me.Split('.').Select(byte.Parse).Reverse().ToArray(), 0); } /// /// 是否base64字符串 /// /// 字符串 /// public static bool IsBase64String(this string me) { // 一个合法的Base64,有着以下特征: // 字符串的长度为4的整数倍。 // 字符串的符号取值只能在A -Z, a -z, 0 -9, +, /, =共计65个字符中,且 = 如果出现就必须在结尾出现。 if (!me.All(x => x.IsBase64Character())) return false; if (me.Length % 4 != 0) return false; var firstEqualSignPos = me.IndexOf('='); if (firstEqualSignPos < 0) return true; var lastEqualSignPos = me.LastIndexOf('='); return lastEqualSignPos == me.Length - 1 && me[firstEqualSignPos..lastEqualSignPos].All(x => x == '='); } /// /// 将一个json字符串反序列化成为jObject对象 /// /// 字符串 /// public static JObject JObject(this string me) { return Newtonsoft.Json.Linq.JObject.Parse(me); } /// /// 中文姓名打马赛克 /// /// /// public static string MaskChineseName(this string me) { if (me.Length == 2) return "*" + me[1..]; return me[..1] + "*" + me[^1..]; } /// /// 对一个手机号进行掩码处理 /// /// 手机号 /// 掩码后的手机号 public static string MaskMobile(this string me) { return new Regex(@"^(\d{3})\d{4}(\d{4})$").Replace(me, "$1****$2"); } /// /// 对一个字符串进行md5hash运算 /// /// 字符串 /// 字符串使用的编码 /// hash摘要的16进制文本形式(无连字符小写) public static string Md5(this string me, Encoding e) { using var md5 = MD5.Create(); return BitConverter.ToString(md5.ComputeHash(e.GetBytes(me))) .Replace("-", string.Empty) .ToLower(CultureInfo.CurrentCulture); } /// /// 判断字符串是否为null或不存在子元素(如果为集合对象);如果为空,返回指定的默认值,否则返回字符串本身 /// /// 指定字符串 /// 指定的默认值 /// 如果为空,返回指定的默认值,否则返回字符串本身 public static string NullOrEmpty(this string me, string defVal) { return me.AsEnumerable().NullOrEmpty() ? defVal : me; } /// /// null或空白字符 /// /// /// public static bool NullOrWhiteSpace(this string me) { return string.IsNullOrWhiteSpace(me); } /// /// 反序列化一个文件获得指定类型的数据对象 /// /// 等待反序列化的json文本 /// 反序列化后生成的对象 public static T Object(this string me) { return JsonConvert.DeserializeObject(me); } /// /// 反序列化一个文件获得指定类型的数据对象 /// /// 等待反序列化的json文本 /// 实际类型 /// 反序列化后生成的对象 public static object Object(this string me, Type type) { return JsonConvert.DeserializeObject(me, type); } /// /// 生成密码 /// /// 密码原文 /// 密文 public static string Pwd(this string me) { return me.Md5Hmac(me.Md5(Encoding.UTF8), Encoding.UTF8); } /// /// 移除字符串中的html标签 /// /// 字符串 /// 处理之后的字符串 public static string RemoveHtmlTag(this string me) { return new Regex(@"<[^>]*>").Replace(me, ""); } /// /// 删除换行符 /// /// /// public static string RemoveWrapped(this string me) { return me.Replace("\r", "").Replace("\n", ""); } /// /// 对一个字符串进行sha1 hash运算 /// /// 字符串 /// 字符串使用的编码 /// hash摘要的16进制文本形式(无连字符小写) public static string Sha1(this string me, Encoding e) { using var sha1 = SHA1.Create(); return BitConverter.ToString(sha1.ComputeHash(e.GetBytes(me))) .Replace("-", string.Empty) .ToLower(CultureInfo.CurrentCulture); } /// /// 截取指定长度的字符串,代替substring /// /// /// /// /// public static string Sub(this string me, int startIndex, int length) { if (startIndex + length > me.Length) length = me.Length - startIndex; return me.Substring(startIndex, length); } /// /// 将连续多个空格替换成一个空格 /// /// /// public static string TrimSpaces(this string me) { var ret = me.Replace(" ", " "); // ReSharper disable once TailRecursiveCall return ret == me ? ret : TrimSpaces(ret); } /// /// url编码 /// /// 字符串 /// url编码后的字符串 public static string Url(this string me) { return Uri.EscapeDataString(me); } /// /// 解码url编码 /// /// url编码后的字符串 /// 解码后的原始字符串 public static string UrlDe(this string me) { return Uri.UnescapeDataString(me); } /// /// 蛇形命名 /// /// /// public static string Snakecase(this string me) { return Regex.Replace(me, "([A-Z])", "-$1").ToLower().TrimStart('-'); } /// /// aes加密 /// /// 要加密的串 /// 密钥 /// 指定要用于加密的块密码模式。 /// 指定在消息数据块短于加密操作所需的完整字节数时要应用的填充类型。 /// public static string Aes(this string me, string key, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7) { using var aes = System.Security.Cryptography.Aes.Create(); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.ECB; aes.Key = key.Hex(); using var encryptor = aes.CreateEncryptor(); var bytes = me.Hex(); var decrypted = encryptor.TransformFinalBlock(bytes, 0, bytes.Length); return decrypted.Base64(); } /// /// aes解密 /// /// 要加密的串 /// 密钥 /// 指定要用于加密的块密码模式。 /// 指定在消息数据块短于加密操作所需的完整字节数时要应用的填充类型。 /// public static string AesDe(this string me, string key, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7) { using var aes = System.Security.Cryptography.Aes.Create(); aes.Padding = PaddingMode.PKCS7; aes.Mode = CipherMode.ECB; aes.Key = key.Hex(); using var encryptor = aes.CreateDecryptor(); var bytes = me.Base64De(); var decrypted = encryptor.TransformFinalBlock(bytes, 0, bytes.Length); return decrypted.HexDe(); } }