C#基本Common方法


1
、通过Key获取配置文件里的配置信息 public static string GetAppSettingValueByKey(string key) { if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[key])) { return ConfigurationManager.AppSettings[key]; } return null; } 2、从适用于URL的Base64编码字符串转换为普通字符串 public static string FromBase64StringForUrl(string base64String) { string temp = base64String.Replace('.', '=').Replace('*', '+').Replace('-', '/'); return Encoding.UTF8.GetString(Convert.FromBase64String(temp)); } 从普通字符串转换为适用于URL的Base64编码字符串 public static string ToBase64StringForUrl(string normalString) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(normalString)).Replace('+', '*').Replace('/', '-').Replace('=', '.'); } 3、取得输入字符串的MD5哈希值 public static string GetMd5Hash(string argInput) { // Create a new instance of the MD5CryptoServiceProvider object. MD5 md5Hasher = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(argInput)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } 4、密码强度认证 public static int PwdStrength(string pwd) { if (pwd.Length >= 6) { if (IsMatch("[a-zA-Z]+", pwd) && IsMatch("[0-9]+", pwd) && IsMatch(@"\W+\D+", pwd)) { return 3; } else if (IsMatch("[a-zA-Z]+", pwd) || IsMatch("[0-9]+", pwd) || IsMatch(@"\W+\D+", pwd)) { if (IsMatch("[a-zA-Z]+", pwd) && IsMatch("[0-9]+", pwd)) { return 2; } else if (IsMatch("[a-zA-Z]+", pwd) && IsMatch(@"\W+\D+", pwd)) { return 2; } else if (IsMatch("[0-9]+", pwd) && IsMatch(@"\W+\D+", pwd)) { return 2; } else { return 1; } } } else { return 0; } return 0; } 5、验证账号格式 ,必须以字母开头的6-20位字母、数字、“_”组合 public static bool VerifyAccount(string account) { Regex r = new Regex(@"^[a-zA-Z][0-9a-zA-Z_]{5,19}$", RegexOptions.None); return r.IsMatch(account); } 6、验证手机格式 public static bool VerifyPhone(string phone) { Regex r = new Regex(@"^1[0-9]{10}$", RegexOptions.None); return r.IsMatch(phone); } 7、验证密码格式,6-20位非空格字符 public static bool VerifyPassword(string password) { Regex r = new Regex(@"^\S{6,20}$", RegexOptions.None); return r.IsMatch(password); } 8、验证姓名 public static bool VerifyName(string name) { Regex r = new Regex(@"^[\u4e00-\u9fa5]{2,8}$", RegexOptions.None); return r.IsMatch(name); } 9、验证身份证 public static bool VerifyIdCard(string idCard) { Regex r = new Regex(@"^\d{17}[\d|x|X]|\d{15}/$", RegexOptions.None); return r.IsMatch(idCard); } 10、验证邮箱 public static bool VerifyEmail(string email) { Regex r = new Regex(@"^[a-zA-Z0-9_\.]+@[a-zA-Z0-9-]+[\.a-zA-Z]+$", RegexOptions.None); }
 /// <summary>
        /// Unicode解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UniDecode(string text)
        {
            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})");
            string a = text.Replace("\\u", "");
            char[] arr = new char[mc.Count];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = (char)Convert.ToInt32(a.Substring(i * 4, 4), 16);
            }
            string c = new string(arr);
            return c;
        }

/// <summary> 
        /// 根据GUID获取16位的唯一字符串 
        /// </summary> 
        /// <param name=\"guid\"></param> 
        /// <returns></returns> 
        public static string GuidTo16String()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:X}", i - DateTime.Now.Ticks);
        }
        /// <summary> 
        /// 根据GUID获取19位的唯一数字序列 
        /// </summary> 
        /// <returns></returns> 
        public static long GuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }

 /// <summary>
        /// 对比两个字符串是否相等(不分大小写)
        /// </summary>
        /// <param name="stringX">字符串1</param>
        /// <param name="stringY">字符串2</param>
        /// <returns>true:相等  false:不相等</returns>
        public static bool Comparer2String(string stringX, string stringY)
        {
            StringComparer stringComparer = StringComparer.InvariantCultureIgnoreCase;
            return stringComparer.Compare(stringX, stringY) == 0;
        }
        public static string getNoncestr()
        {
            Random random = new Random();
            return MD5Helper.GetMd5Hash(random.Next(10000).ToString());
        }
        public static string getTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        public static DateTime GetRealTime(string timeStamp)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNowTime = new TimeSpan(lTime);
            return Convert.ToDateTime(startTime.Add(toNowTime).ToString("yyyy-MM-dd HH:mm:ss"));
        } 

 public class MD5Helper
    {
        /// <summary>
        /// 根据salt获取密码Md5(密码MD5格式:MD5(MD5(Password) + Salt))
        /// </summary>
        /// <param name="md5Password">密码</param>
        /// <param name="salt">验证方式</param>
        /// <returns>密码MD5</returns>
        public static string GetPasswordMd5(string md5Password)
        {
            return GetMd5Hash(md5Password);
        }

        /// <summary>
        /// 取得输入字符串的MD5哈希值
        /// </summary>
        /// <param name="argInput">输入字符串</param>
        /// <returns>MD5哈希值</returns>
        public static string GetMd5Hash(string argInput)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(argInput));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
    }

public class EncryptUtil
    {

        //默认密钥向量 
        private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

        /// <summary>
        /// AES加密算法
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <param name="strKey">密钥</param>
        /// <returns>返回加密后的密文字节数组</returns>
        public static string AESEncrypt(string plainText, string strKey)
        {
            //分组加密算法
            SymmetricAlgorithm des = Rijndael.Create();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
            des.Key = Encoding.UTF8.GetBytes(strKey);//设置密钥及密钥向量
            des.IV = _key1;
            des.Mode = CipherMode.ECB;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
            cs.Close();
            ms.Close();

            return Convert.ToBase64String(cipherBytes); ;
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">密文字节数组</param>
        /// <param name="strKey">密钥</param>
        /// <returns>返回解密后的字符串</returns>
        public static string AESDecrypt(string data, string strKey)
        {
            Byte[] cipherText = Convert.FromBase64String(data);
            SymmetricAlgorithm des = Rijndael.Create();
            des.Key = Encoding.UTF8.GetBytes(strKey);
            des.IV = _key1;
            des.Mode = CipherMode.ECB;
            byte[] decryptBytes = new byte[cipherText.Length];
            MemoryStream ms = new MemoryStream(cipherText);
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
            cs.Read(decryptBytes, 0, decryptBytes.Length);
            cs.Close();
            ms.Close();
            return Encoding.UTF8.GetString(decryptBytes); ;
        }
     
    }

 public class Base64Common
    {
        ///
        /// Base64加密
        ///
        ///
        ///
        public static string Base64Code(string Message)
        {
            byte[] bytes = Encoding.Default.GetBytes(Message);
            return Convert.ToBase64String(bytes);
        }
        ///
        /// Base64解密
        ///
        ///
        ///
        public static string Base64Decode(string Message)
        {
            byte[] bytes = Convert.FromBase64String(Message);
            return Encoding.Default.GetString(bytes);
        }
    }

 

 

 

 

posted on 2017-11-09 11:28  D-Z-K  阅读(916)  评论(0编辑  收藏  举报

导航