using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace Taolx.JuneAir.Common.Extensions
{
///
/// String 扩展类
///
public static class StringExtension
{
private static readonly Regex WebUrlExpression = new Regex(@"(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex EmailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex StripHTMLExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly char[] IllegalUrlCharacters = new[] { ';', '/', '\\', '?', ':', '@', '&', '=', '+', '$', ',', '<', '>', '#', '%', '.', '!', '*', '\'', '"', '(', ')', '[', ']', '{', '}', '|', '^', '`', '~', '–', '‘', '’', '“', '”', '?', '?' };
///
/// 默认密钥-密钥的长度必须是32
///
private const string PublicKey = "1qaz2wsx3edc4rfv";
///
/// 默认向量
///
private const string Iv = "abcdefghijklmnop";
///
/// 为空或者""
///
///
///
public static bool IsNullOrEmpty(this string source)
{
return string.IsNullOrEmpty(source);
}
///
/// ToTrim
///
///
///
///
public static string ToTrim(this string source, string defalutVal = "")
{
return (source ?? defalutVal).Trim();
}
///
/// string类型日期转换成datetiem类型
///
///
/// 转换失败返回null
public static DateTime? ToNullbaleDateTime(this string str)
{
if (string.IsNullOrEmpty(str))
return null;
DateTime dateTime;
return DateTime.TryParse(str, out dateTime) ? dateTime : (DateTime?)null;
}
///
/// 将当前字符串从指定索引位置将指定长度的字符替换为新字符
///
/// 当前字符串
/// 替换起始索引位置
/// 指定长度
/// 替换的字符
///
public static string ReplaceStr(this string oldStr, int index, int length, char newChar = '*')
{
if (oldStr == null)
return "";
if (index < 0)
index = 0;
if (length > oldStr.Length)
length = oldStr.Length;
string keepStr = oldStr.Substring(length - index, oldStr.Length - length);
return keepStr.PadLeft(oldStr.Length, newChar);
}
///
/// 获取32位长度的Md5摘要
///
///
///
///
public static string Get32Md5(this string input, Encoding encoding = null)
{
if (encoding == null) encoding = Encoding.UTF8;
StringBuilder buff = new StringBuilder(32);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(encoding.GetBytes(input));
foreach (byte t1 in t)
buff.Append(t1.ToString("x").PadLeft(2, '0'));
return buff.ToString();
}
///
/// md5去掉"-"转成string
///
public static string ToMD5(this string str)
{
//return System.Security.Cryptography.MD5.Create(str).ToString();
//return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
//System.Security.Cryptography.MD5 md55 = new System.Security.Cryptography.MD5CryptoServiceProvider();
if (string.IsNullOrEmpty(str)) return str;
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");
return encoded.ToLower();
}
///
/// 是否为WebUrl地址
///
///
///
public static bool IsWebUrl(this string target)
{
return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target);
}
///
/// 是否为Email地址
///
///
///
public static bool IsEmail(this string target)
{
return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target);
}
///
/// string转Guid
///
///
///
public static Guid ToGuid(this string target)
{
Guid result = Guid.Empty;
if ((!string.IsNullOrEmpty(target)) && (target.Trim().Length == 22))
{
string encoded = string.Concat(target.Trim().Replace("-", "+").Replace("_", "/"), "==");
try
{
byte[] base64 = Convert.FromBase64String(encoded);
result = new Guid(base64);
}
catch (FormatException)
{
}
}
return result;
}
///
/// 是否为数字
///
///
///
public static Boolean IsNumeric(this String str)
{
long temp_big_int;
var is_number = long.TryParse(str, out temp_big_int);
return is_number;
}
///
/// string to int
///
///
///
///
public static int ToInt(this String str, int defVal = 0)
{
int.TryParse(str, out defVal);
return defVal;
}
///
/// string to long
///
///
///
///
public static long ToLong(this String str, long defVal = 0)
{
long.TryParse(str, out defVal);
return defVal;
}
///
/// string to decimal
///
///
///
///
public static decimal ToDecimal(this String str, decimal defVal = 0)
{
decimal.TryParse(str, out defVal);
return defVal;
}
///
/// string to float
///
///
///
///
public static float ToFloat(this String str, float defVal = 0)
{
float.TryParse(str, out defVal);
return defVal;
}
///
/// string to double
///
///
///
///
public static double ToDouble(this String str, double defVal = 0)
{
double.TryParse(str, out defVal);
return defVal;
}
private static DateTime minValue = DateTime.MinValue;
///
/// string to datetime
///
///
/// 日期格式
/// 默认日期
///
public static DateTime ToDateTime(this string str, string format, DateTime defVal)
{
try
{
DateTime dt = DateTime.ParseExact(str, format, System.Globalization.CultureInfo.InvariantCulture);
return dt;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return defVal;
}
}
#region 加解密
///
/// AES加密
///
/// 需要加密字符串
/// 加密后字符串
public static String Encrypt(this string str)
{
try
{
return Encrypt(str, PublicKey);
}
catch (Exception e)
{
return str;
}
}
///
/// AES解密
///
/// 需要解密字符串
/// 解密后字符串
public static String Decrypt(this string str)
{
try
{
return Decrypt(str, PublicKey);
}
catch (Exception e)
{
return str;
}
}
///
/// AES加密
///
/// 需要加密的字符串
/// 32位密钥
/// 加密后的字符串
public static string Encrypt(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = System.Text.Encoding.UTF8.GetBytes(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
///
/// AES解密
///
/// 需要解密的字符串
/// 32位密钥
/// 解密后的字符串
public static string Decrypt(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = Convert.FromBase64String(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return System.Text.Encoding.UTF8.GetString(resultArray);
}
///
/// AES加密
///
/// 需要加密字符串
/// 加密后字符串
public static String EncryptToString(this string str)
{
try
{
return EncryptToString(str, PublicKey);
}
catch (Exception e)
{
return str;
}
}
///
/// AES加密
///
/// 需要加密的字符串
/// 32位密钥
/// 加密后的字符串
public static string EncryptToString(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
Byte[] toEncryptArray = System.Text.Encoding.UTF8.GetBytes(str);
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
StringBuilder builder = new StringBuilder();
int num2 = resultArray.Length - 1;
for (int i = 0; i <= num2; i++)
{
builder.AppendFormat("{0:X2}", resultArray[i]);
}
return builder.ToString();
// return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
///
/// AES解密
///
/// 需要解密字符串
/// 解密后字符串
public static String DecryptToString(this string str)
{
try
{
return DecryptToString(str, PublicKey);
}
catch (Exception e)
{
return str;
}
}
///
/// AES解密
///
/// 需要解密的字符串
/// 32位密钥
/// 解密后的字符串
public static string DecryptToString(this string str, string key)
{
Byte[] keyArray = System.Text.Encoding.UTF8.GetBytes(key);
int halfInputLength = str.Length / 2;
Byte[] toEncryptArray = new Byte[halfInputLength];
for (int x = 0; x < halfInputLength; x++)
{
int i = (Convert.ToInt32(str.Substring(x * 2, 2), 16));
toEncryptArray[x] = (byte)i;
}
var rijndael = new System.Security.Cryptography.RijndaelManaged();
rijndael.Key = keyArray;
rijndael.Mode = System.Security.Cryptography.CipherMode.ECB;
rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return System.Text.Encoding.UTF8.GetString(resultArray);
// return UTF8Encoding.UTF8.GetString(resultArray);
}
#endregion
private static readonly Regex RepalceHttpToHttpsRegex = new Regex("^http(\\:\\/\\/){1}", RegexOptions.IgnoreCase);
///
/// 替换http为https
///
/// targetProtocol: https
///
public static string ToHttpsUrl(this string url)
{
url = url.ToTrim();
string strOutput = RepalceHttpToHttpsRegex.Replace(url, "https://");
return strOutput;
}
private static readonly Regex RemoveHttpOrHttpsRegex = new Regex("^http(s?)(\\:\\/\\/){1}", RegexOptions.IgnoreCase);
///
//////
/// targetProtocol: https
///
public static string ToRemoveUrlProtocol(this string url)
{
url = url.ToTrim();
string strOutput = RemoveHttpOrHttpsRegex.Replace(url, "//");
return strOutput;
}
}
}