using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.IO; using System.Web; namespace NCC.Code { public static class StringExtension { #region 字符串判断 /// /// 是否为用户上行短信验证码 /// /// /// public static bool M5_IsSMSReplyCode(this string str) { str = str.Trim(); if (str.Length != 6) { return false; } int tmp = 0; int.TryParse(str, out tmp); if (tmp <= 0) { return false; } return true; } /// /// 判断是否是手机号 /// /// /// public static bool M5_IsMobile(this string str) { return new Regex("^1[3,4,5,7,8,9]\\d{9}$").IsMatch(str); } #endregion #region 字符串处理 public static string StrCharcoder(this string str) { return str.Replace("\\", "").Replace("\"", "").Trim(); } public static string M5_RemoveEnter(this string str) { return str.Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); } #region 字符串转码 /// /// Base64加密 /// /// 加密采用的编码方式 /// 待加密的明文 /// public static string M5_EncodeBase64(this string source, Encoding encode) { string enstring = ""; byte[] bytes = encode.GetBytes(source); try { enstring = Convert.ToBase64String(bytes); } catch { enstring = source; } return enstring; } /// /// 中文转unicode /// /// public static string StrDecode(this string str) { string outStr = ""; if (!string.IsNullOrEmpty(str)) { for (int i = 0; i < str.Length; i++) { outStr += "/u" + ((int)str[i]).ToString("x"); } } return outStr; } /// /// unicode转中文 /// /// public static string StrEncode(this string str) { string outStr = ""; if (!string.IsNullOrEmpty(str)) { string[] strlist = str.Replace("/", "").Split('u'); try { for (int i = 1; i < strlist.Length; i++) { //将unicode字符转为10进制整数,然后转为char中文字符 outStr += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber); } } catch (FormatException ex) { outStr = ex.Message; } } return outStr; } /// /// unicode转中文(符合js规则的) /// /// public static string StrJsDecode(this string str) { string outStr = ""; Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})"); outStr = reg.Replace(str, delegate (Match m1) { return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString(); }); return outStr; } /// /// 中文转unicode(符合js规则的) /// /// public static string StrJsEncode(this string str) { string outStr = ""; if (!string.IsNullOrEmpty(str)) { for (int i = 0; i < str.Length; i++) { if (Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fa5]")) { outStr += "\\u" + ((int)str[i]).ToString("x"); } else { outStr += str[i]; } } } return outStr; } /// /// url字符串编码 /// /// /// public static string M5_UrlEncode(this string str) { Encoding utf8 = Encoding.UTF8; return HttpUtility.UrlEncode(str, utf8); } /// /// url字符串解码 /// /// /// public static string M5_UrlDecode(this string str) { Encoding utf8 = Encoding.UTF8; return HttpUtility.UrlDecode(str, utf8); } #endregion #region 字符串截取 /// /// 返回截取固定长度字符串 /// /// /// /// public static string SubString(this string queryString, int num) { if (queryString == null) return string.Empty; num = num > queryString.Length ? queryString.Length : num; return queryString.Substring(0, num); } /// /// 返回截取固定长度字符串 /// /// /// /// public static string SubString(this string queryString, int num, string defaultstr) { if (queryString == null) return string.Empty; num = num > queryString.Length ? queryString.Length : num; return queryString.Substring(0, num) + defaultstr; } /// /// md532加密码处理 /// 规则:截前2位和后3位 /// /// 加密字符串 /// public static string Md532SubString(this string queryString) { if (queryString == null) return string.Empty; int len = queryString.Length; if (len != 32) return queryString; queryString = queryString.Substring(2, 27); return queryString; } #endregion #region 字符串过滤 /// /// 返回过滤不安全字符<> htmlecode /// /// 字符串 /// public static string StrFilter(this string queryString) { if (queryString == null) return string.Empty; return queryString.Replace("<", "<") .Replace(">", ">"); } /// /// 返回过滤不安全字符<>转全角 /// /// 字符串 /// public static string StrFilterFull(this string queryString) { if (queryString == null) return string.Empty; return queryString.Replace("<", "<") .Replace(">", ">"); } /// /// 返回过滤不安全字符去除<>包含里面的内容 /// /// 过滤的内容 /// public static string StrFilter(this string queryString, bool replace) { if (queryString == null) return string.Empty; return Regex.Replace(queryString, "<.*?>", ""); } /// /// lucene保留关键字过滤 /// /// 过滤关键字 /// public static string LuceneStrStaticFilter(this string queryString) { if (queryString == null) return string.Empty; return queryString.Replace("+", "") .Replace("-", "") .Replace("&", "") .Replace("|", "") .Replace("!", "") .Replace("(", "") .Replace(")", "") .Replace("{", "") .Replace("}", "") .Replace("[", "") .Replace("]", "") .Replace("^", "") .Replace("~", "") .Replace("*", "") .Replace("?", "") .Replace("'", "") .Replace(":", "") .Replace("\\", "") .Replace("\"", "") .Replace("AND", "") .Replace("OR", "") .Replace("NOT", ""); } /// /// SQL防注入 /// /// 要过滤的字符串 /// 如果参数存在不安全字符,则返回true public static bool IsSqlTextSafe(this string queryString) { if (queryString == null) { return false; } string word = @"and|exec|select|update|delete|drop|chr|mid|master|truncate|char|declare|join|cmd";//这里加要过滤的SQL字符 if (Regex.IsMatch(queryString.ToLower(), word.ToLower(), RegexOptions.IgnoreCase)) return true; return false; } /// /// SQl防止注入 /// /// /// public static bool IsSqlTextSafe(this string queryString, bool old) { if (queryString == null) { return false; } //过滤关键字 string StrKeyWord = @"exec|select|insert|delete|from|count\(|drop table|update|truncate|asc\(|mid\(|char\(|xp_cmdshell|exec master|netlocalgroup administrators|net user|""|or|and"; //过滤关键字符 string StrRegex = @"[;|%|\@|*|!|']"; if (Regex.IsMatch(queryString.ToLower(), StrKeyWord.ToLower(), RegexOptions.IgnoreCase) || Regex.IsMatch(queryString.ToLower(), StrRegex.ToLower())) return true; return false; } /// /// SQL防注入 /// /// 要过滤的字符串 /// 如果参数存在不安全字符,则返回true public static string SqlTextFilter(this string queryString) { if (queryString == null) return string.Empty; return queryString//.Replace("and", "") .Replace("exec", "") //.Replace("select", "") .Replace("chr", "") .Replace("mid", "") .Replace("master", "") .Replace("or", "") .Replace("truncate", "") .Replace("char", "") .Replace("declare", "") .Replace("join", "") .Replace("cmd", "") .Replace(";", "") .Replace("'", "") .Replace("update", "") .Replace("insert", "") .Replace("drop", "") .Replace("delete", ""); } public static string ArryJoinString(this List arry, string split = ",") { if (arry == null || arry.Count < 1) return string.Empty; return String.Join(split, arry); } public static string ArryJoinString(this List arry, string split = ",") { if (arry == null || arry.Count < 1) return string.Empty; return String.Join(split, arry); } public static string ArryJoinStringForSql(this List arry, string split = ",") { if (arry == null || arry.Count < 1) return string.Empty; List tmp = new List(); foreach (var item in arry) { tmp.Add($"'{item}'"); } return String.Join(split, tmp); } //public static string SqlCharIndexFilter(this List arry, string field, string other = "") //{ // string where = string.Empty; // List list = new List(); // foreach (int item in arry) // { // list.Add($" CHARINDEX(',{item},',','+{field}+',') > 0 "); // } // if (other.IsNotNullOrEmpty()) // { // list.Add(other); // } // where = $" and ( {list.ArryJoinString(" or ")}) "; // return where; //} //public static string SqlCharIndexFilter(this List arry, string field) //{ // string where = string.Empty; // List list = new List(); // foreach (string item in arry) // { // list.Add($" CHARINDEX(','{item}',',','+{field}+',') > 0 "); // } // where = $" and ( {list.ArryJoinString(" or ")}) "; // return where; //} #endregion #region 字符串转换 public static string[] M5_Split(this string str, string split_str) { try { return str.Split(new[] { split_str }, StringSplitOptions.None); } catch (Exception ex) { return new string[] { }; } } public static List M5_SplitToList(this string str, string split_str) { try { return str.Split(new[] { split_str }, StringSplitOptions.None).ToList(); } catch (Exception ex) { return new List(); } } public static List M5_SplitToIntList(this string str, string split_str) { try { return M5_SplitToList(str, split_str).Select(o => o.ObjToInt()).ToList(); } catch (Exception ex) { return new List(); } } /// ///返回 List<int>数组转换成string字符串 中间 ',' 号隔开 /// /// 数组 /// public static string ListToString(this List list) { if (list == null || list.Count == 0) return string.Empty; StringBuilder retStr = new StringBuilder(); foreach (int item in list) { retStr.AppendFormat(",{0}", item.ToString()); } return retStr.Remove(0, 1).ToString(); } /// ///返回 List<int>数组转换成string字符串 中间 ',' 号隔开 /// /// 数组 /// public static string ListToString(this List list) { if (list == null || list.Count == 0) return string.Empty; StringBuilder retStr = new StringBuilder(); foreach (string item in list) { retStr.AppendFormat(",'{0}'", item.ToString()); } return retStr.Remove(0, 1).ToString(); } /// ///返回 List<int>数组转换成string字符串 中间 ',' 号隔开 /// /// 数组 /// public static string ListToStrings(this List list) { if (list == null || list.Count == 0) return string.Empty; StringBuilder retStr = new StringBuilder(); foreach (string item in list) { retStr.AppendFormat(",{0}", item.ToString()); } return retStr.Remove(0, 1).ToString(); } /// ///返回 List<int>数组转换成string字符串 按照指定分隔符转化 /// /// 数组 /// 分隔符 /// public static string ListToString(this List list, byte split) { if (list == null || split == null || list.Count == 0) return string.Empty; StringBuilder retStr = new StringBuilder(); foreach (int item in list) { retStr.AppendFormat("{0}{1}", split, item.ToString()); } return retStr.Remove(0, 1).ToString(); } /// /// 时间撮转换成 datetime时间 /// /// 时间戳 /// public static DateTime TimeStampConvertDateTime(this string timeStamp) { DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dateTimeStart.Add(toNow); } /// /// 时间转换成时间撮 /// /// 时间 /// public static string DateTimeConvertTimeStamp(this DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (time - startTime).TotalSeconds.ToString().Substring(0, 10); } /// /// 日期转换成unix时间戳 /// /// /// public static string DateTimeToUnixTimestamp(this DateTime dateTime) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return ((int)(dateTime - startTime).TotalSeconds).ToString(); } /// /// unix时间戳转换成日期 /// /// 时间戳(秒) /// public static DateTime UnixTimestampToDateTime(this string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } #endregion #region 字符串加(解)密 /// /// SHA1加密 /// public static string SHA1Encrypt(this string encryptString) { byte[] StrRes = Encoding.Default.GetBytes(encryptString); HashAlgorithm iSHA = new SHA1CryptoServiceProvider(); StrRes = iSHA.ComputeHash(StrRes); StringBuilder EnText = new StringBuilder(); foreach (byte iByte in StrRes) { EnText.AppendFormat("{0:x2}", iByte); } return EnText.ToString(); } public static string SHA1EncryptRoWx(this string encryptString) { byte[] cleanBytes = Encoding.Default.GetBytes(encryptString); byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes); return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); } /// /// 返回MD5加密后的字符串 /// /// 原始字符串 /// MD5加密字符串 public static string StringToMd5(this string encryptString) { byte[] b = Encoding.Default.GetBytes(encryptString); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } public static string StringToMd5(this string encryptString, Encoding ecode) { byte[] b = ecode.GetBytes(encryptString); b = new MD5CryptoServiceProvider().ComputeHash(b); string ret = ""; for (int i = 0; i < b.Length; i++) ret += b[i].ToString("x").PadLeft(2, '0'); return ret; } /// /// RSA加密 /// /// /// /// public static string RSAEncrypt(this string content, string publickey) { if (content.IsNull() || publickey.IsNull()) { return string.Empty; } RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); byte[] bytearr = Convert.FromBase64String(publickey); RSAKeyInfo.Modulus = bytearr.ToList().GetRange(29, bytearr.Length - 34).ToArray(); RSAKeyInfo.Exponent = Convert.FromBase64String("AQAB"); RSA.ImportParameters(RSAKeyInfo); byte[] bytes = RSA.Encrypt(UTF8Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(bytes); } ///// ///// RSA加密 ///// ///// 公钥 ///// MD5加密后的数据 ///// RSA公钥加密后的数据 //public static string XFRSAEncrypt(this string content, string publickey) //{ // if (content.IsNull() || publickey.IsNull()) // { // return string.Empty; // } // //publickey = "w5x7MPzqx+zYboYDp3RCVOUu0DlvN4qXCmjfI5LX6nw4E4shN8DWxC/Tk9h4CaB+ycIEN+6qiZpEf9g50nhS9LI2sEDQwYsRfGCsnkOvBUwF2efaNZhtelWSRZpqiyvt9c0By53qXuHtNrpZEh+pFc4Eh34eFv2HucBXxyHchpM=AQAB"; // RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); // byte[] cipherbytes; // rsa.FromXmlString(publickey); // cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); // return Convert.ToBase64String(cipherbytes); //} public static string XFRSAEncrypt(this string content, string publickey) { if (content.IsNull() || publickey.IsNull()) { return string.Empty; } //publickey = "w5x7MPzqx+zYboYDp3RCVOUu0DlvN4qXCmjfI5LX6nw4E4shN8DWxC/Tk9h4CaB+ycIEN+6qiZpEf9g50nhS9LI2sEDQwYsRfGCsnkOvBUwF2efaNZhtelWSRZpqiyvt9c0By53qXuHtNrpZEh+pFc4Eh34eFv2HucBXxyHchpM="; RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); RSAKeyInfo.Modulus = Convert.FromBase64String(publickey); RSAKeyInfo.Exponent = Convert.FromBase64String("AQAB"); RSA.ImportParameters(RSAKeyInfo); byte[] bytes = RSA.Encrypt(UTF8Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(bytes); } /// /// RSA解密 /// /// 私钥 /// 待解密的数据 /// 解密后的结果 public static string XFRSADecrypt(this string content, string privatekey) { if (content.IsNull() || privatekey.IsNull()) { return string.Empty; } //privatekey = "w5x7MPzqx+zYboYDp3RCVOUu0DlvN4qXCmjfI5LX6nw4E4shN8DWxC/Tk9h4CaB+ycIEN+6qiZpEf9g50nhS9LI2sEDQwYsRfGCsnkOvBUwF2efaNZhtelWSRZpqiyvt9c0By53qXuHtNrpZEh+pFc4Eh34eFv2HucBXxyHchpM=AQAB

yRXQLm3u9b0WyzJeMzS7kvdWDlMxFh0gjtH8hPyFWkXi/eI1ek7YLL2lgopimq4zfVK3jWHF4h5aH+ayXdP0yw==

+Qf5qTfNDsR6xd028uVsE9RKyFqhiyfgs7DT3XDgIXgZ0N21ztplup7pp9+6IHaC1qJ8NxaVzeFZ7fBmzCPEWQ==HRl3AwENr6opfkZPs4FSE7aPUYtgcx7L818X9/bDJYkvjCYMLyLxzae0J+v20QOcl+o8fc1EYbCawjsUXNereQ==mSc3esNvoCJj4yYeMhm4cyV/bGKYsQ0wWzJnyesuXEcRkWuY8YNNRw2OY4jrXiWkZ738KKECNmDePsA3aFqi2Q==QdAD7Nmv3llzZaipbECCLWiyQyuJfVmOFvoPgJiIeEVZnXr86fsyXB8jyn2cctvdSqeAu1OXOYBsL1vkQ29efQ==Sbnn4J3i67mEFZwjMnEqMw8yZr7PAVMV/JFsUN8ezD1HcW5F9dqT19vi1d2H2LEKOIcMyfwFgNmJKdpYaNB7Cx+dcvJ+iZWfFrRrjqz8l9GXsTycyyw2r/OUJu0UV6khW6qRL7kiFYj7Dny8ZvccwVOjBT56ja76LpOJ1ogRT7E=
"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); try { cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); } catch (Exception) { return string.Empty; } return Encoding.UTF8.GetString(cipherbytes); } #endregion #region 字符串格式化 public static string StrToString(this object str) { return str == null ? string.Empty : str.ToString(); } /// /// datetime转换 /// /// /// public static string TimeToString(this DateTime time) { return time == null ? string.Empty : time.ToString("yyyy-MM-dd HH:mm:ss"); } #endregion public static string ArryJoinStringDoubleSql(this List arry, string split = ",") { if (arry == null || arry.Count < 1) return string.Empty; List tmp = new List(); foreach (var item in arry) { tmp.Add($"\"{item}\""); } return String.Join(split, tmp); } public static List StringToArry(this string arry, char split = ',') { List list = new List(); try { list = arry.Split(split).ToList(); } catch (Exception) { } return list; } #endregion } }