StrUtils类:字符串处理/加密解密函数库
作者:C/S框架网  发布日期:2011-07-14 21:08:41
StrUtils类:字符串处理/加密解密函数库

   
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;

namespace globals
{

   public class StrUtils
   {
      private static string ENCRYP_KEY = "MYKEY";
      
      /// <summary>
      /// 对象转换字符串
      /// </summary>
      public static string ToString(object o)
      {
         if (o == null)
         return string.Empty;
         else
         return o.ToString();
      }
      
      /// <summary>
      /// 将16进制的字符串转换为10进制字节数组
      /// </summary>
      public static byte[] StrToByte(string str)
      {
         byte[] buffer = new byte[str.Length / 2];
         for (int i = 0; i < (str.Length / 2); i++)
         {
            int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
            buffer[i] = (byte)num2;
         }
         return buffer;
      }
      
      /// <summary>
      /// 将10进制字节数组转换为16进制的字符串.
      /// </summary>
      public static string ByteToStr(byte[] bs)
      {
         StringBuilder sb = new StringBuilder();
         foreach (byte b in bs)
         sb.AppendFormat("{0:X2}", b);
         return sb.ToString();
      }
      
      /// <summary>
      /// 字符串加密.由DESCryptoServiceProvider对象加密
      /// </summary>
      public static string Encode(string str)
      {
         try
         {
            string key = ENCRYP_KEY;
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            byte[] bytes = Encoding.Default.GetBytes(str);
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            foreach (byte num in stream.ToArray())
            {
               builder.AppendFormat("{0:X2}", num);
            }
            stream.Close();
            return builder.ToString();
         }
         catch
         {
            return string.Empty;
         }
      }
      
      /// <summary>
      /// 字符串解密.由DESCryptoServiceProvider对象解密
      /// </summary>
      public static string Decode(string str)
      {
         try
         {
            string key = ENCRYP_KEY;
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            byte[] buffer = new byte[str.Length / 2];
            for (int i = 0; i < (str.Length / 2); i++)
            {
               int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
               buffer[i] = (byte)num2;
            }
            MemoryStream stream = new MemoryStream();
            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            stream.Close();
            return Encoding.Default.GetString(stream.ToArray());
         }
         catch
         {
            return string.Empty;
         }
      }
      
      
      /// <summary>
      /// MD5加密,Use object MD5
      /// </summary>
      public static string encryptMD5(string content)
      {
         string retContent = "";
         
         MD5 md5 = MD5.Create();
         // 加密后是一个字节类型的数组
         byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(content));
         
         // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
         for (int i = 0; i < s.Length; i++)
         {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,
            //如果使用大写(X)则格式后的字符是大写字符
            retContent = retContent + s[i].ToString("X");
         }
         return retContent;
      }
      
      /// <summary>
      /// MD5不可逆加密.use MD5CryptoServiceProvider
      /// </summary>
      public static string GenerateMD5Hash(string input)
      {
         MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
         
         byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
         
         StringBuilder sBuilder = new StringBuilder();
         
         for (int i = 0; i < data.Length; i++)
         {
            sBuilder.Append(data[i].ToString("x2"));
         }
         
         return sBuilder.ToString();
      }
      
      /// <summary>
      /// 获取字符串长度
      /// </summary>
      public static int GetStringLength(string content)
      {
         return System.Text.Encoding.Default.GetByteCount(content);
      }
      
      /// <summary>
      /// 由指定长度length取左边字符串
      /// </summary>
      public static string GetLeftStr(string content, int length)
      {
         return SubString(content, length, false);
      }
      
      /// <summary>
      /// 截取字符串.包含由中文英文标点符号组成的字符串
      /// </summary>
      /// <param name="content">原始字符串</param>
      /// <param name="length">截取长度</param>
      /// <param name="addDot">尾部加"..."</param>
      /// <returns>截取后的字符串</returns>
      public static string SubString(string content, int length, bool addDot)
      {
         Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
         char[] stringChar = content.ToCharArray(); //转换为字节数组
         StringBuilder sb = new StringBuilder();
         int nLength = 0;
         bool isCut = false;
         for (int i = 0; i < stringChar.Length; i++)
         {
            if (regex.IsMatch((stringChar[i]).ToString()))
            {
               sb.Append(stringChar[i]);
               nLength += 2;
            }
            else
            {
               sb.Append(stringChar[i]);
               nLength = nLength + 1;
            }
            
            if (nLength >= length)
            {
               isCut = true;
               break;
            }
         }
         if (isCut && addDot)
         return sb.ToString() + "...";
         else
         return sb.ToString();
      }
      
   }
   
}


上一篇 下一篇