C#常用編碼工具類(lèi):支持base64,md5,des,crc32

2010-08-28 10:50:35來(lái)源:西部e網(wǎng)作者:

常用編碼工具類(lèi),支持base64,md5,des,crc32 
支持從文件到文件,從字符串到字符串的方式操作 
以下是源碼

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;

namespace YNEC.Services.Encrypt {
  /**//// <summary>
  /// CRC 效驗(yàn)
  /// 快速檢測(cè)算法
  /// </summary>
  public class CRC32{

    protected ulong[] crc32Table;

    /**//// <summary>
    /// 構(gòu)造:初始化效驗(yàn)表
    /// </summary>
    public CRC32() {
      const ulong ulPolynomial = 0xEDB88320
      ulong dwCrc;
      crc32Table = new ulong[256];
      int i,j;
      for(i = 0 i < 256 i++) {
        dwCrc = (ulong)i;
        for(j = 8 j > 0 j--) {
          if((dwCrc & 1)==1)
            dwCrc = (dwCrc >> 1) ^ ulPolynomial;
          else
            dwCrc >>= 1
        }
        crc32Table[i] = dwCrc;
      }
    }

    /**//// <summary>
    /// 字節(jié)數(shù)組效驗(yàn)
    /// </summary>
    /// <param name="buffer">ref 字節(jié)數(shù)組</param>
    /// <returns></returns>
    public ulong ByteCRC(ref byte[] buffer) {
      ulong ulCRC = 0xffffffff 
      ulong len; 
      len = (ulong)buffer.Length;
      for (ulong buffptr=0 buffptr < len; buffptr++) {
             ulong tabPtr = ulCRC & 0xFF
        tabPtr = tabPtr ^ buffer[buffptr];
        ulCRC = ulCRC >> 8
        ulCRC = ulCRC ^ crc32Table[tabPtr];
      }
      return ulCRC ^ 0xffffffff 
    }


    /**//// <summary>
    /// 字符串效驗(yàn)
    /// </summary>
    /// <param name="sInputString">字符串</param>
    /// <returns></returns>
    public ulong StringCRC(string sInputString){
      byte[] buffer = Encoding.Default.GetBytes(sInputString);
      return ByteCRC(ref buffer);
    }

    /**//// <summary>
    /// 文件效驗(yàn)
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <returns></returns>
    public ulong FileCRC(string sInputFilename){
      FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open,  System.IO.FileAccess.Read);
      byte[] bInput = new byte[inFile.Length];
      inFile.Read(bInput,0,bInput.Length);
      inFile.Close();

      return ByteCRC(ref bInput);
    }

  }
  /**//// <summary>
  /// MD5 無(wú)逆向編碼
  /// 獲取唯一特征串,可用于密碼加密
  /// (無(wú)法還原)
  /// </summary>
  public class MD5 {

    public MD5(){
    }

    /**//// <summary>
    /// 獲取字符串的特征串
    /// </summary>
    /// <param name="sInputString">輸入文本</param>
    /// <returns></returns>
    public string HashString(string sInputString){
      System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
      string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(sInputString))).Replace("-","");
      return encoded;
    }

    /**//// <summary>
    /// 獲取文件的特征串
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <returns></returns>
    public string HashFile(string sInputFilename){
      System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
      FileStream inFile = new System.IO.FileStream(sInputFilename, System.IO.FileMode.Open,  System.IO.FileAccess.Read);
      byte[] bInput = new byte[inFile.Length];
      inFile.Read(bInput,0,bInput.Length);
      inFile.Close();

      string encoded = BitConverter.ToString(md5.ComputeHash(bInput)).Replace("-","");
      return encoded;
    }

  }

  /**//// <summary>
  /// Base64 UUEncoded 編碼
  /// 將二進(jìn)制編碼為ASCII文本,用于網(wǎng)絡(luò)傳輸
  /// (可還原)
  /// </summary>
  public class BASE64{

    public BASE64(){
    }

    /**//// <summary>
    /// 解碼字符串
    /// </summary>
    /// <param name="sInputString">輸入文本</param>
    /// <returns></returns>
    public string DecryptString(string sInputString){
      char[] sInput = sInputString.ToCharArray();
      try{
        byte[] bOutput = System.Convert.FromBase64String(sInputString);
        return Encoding.Default.GetString(bOutput);
      }
      catch ( System.ArgumentNullException ) {
        //base 64 字符數(shù)組為null
        return ""
      }
      catch ( System.FormatException ) {
        //長(zhǎng)度錯(cuò)誤,無(wú)法整除4
        return ""
      }      
    }

    /**//// <summary>
    /// 編碼字符串
    /// </summary>
    /// <param name="sInputString">輸入文本</param>
    /// <returns></returns>
    public string EncryptString(string sInputString){
      byte[] bInput = Encoding.Default.GetBytes(sInputString);
      try {
        return System.Convert.ToBase64String(bInput,0,bInput.Length);
      }
      catch (System.ArgumentNullException) {
        //二進(jìn)制數(shù)組為NULL.
        return ""
      }
      catch (System.ArgumentOutOfRangeException) {
        //長(zhǎng)度不夠
        return ""
      }
    }

    /**//// <summary>
    /// 解碼文件
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <param name="sOutputFilename">輸出文件</param>
    public void DecryptFile(string sInputFilename,string sOutputFilename) {
      System.IO.StreamReader inFile;     
      char[] base64CharArray;

      try {
        inFile = new System.IO.StreamReader(sInputFilename,
          System.Text.Encoding.ASCII);
        base64CharArray = new char[inFile.BaseStream.Length];
        inFile.Read(base64CharArray, 0, (int)inFile.BaseStream.Length);
        inFile.Close();
      }
      catch {//(System.Exception exp) {
        return
      }

      // 轉(zhuǎn)換Base64 UUEncoded為二進(jìn)制輸出
      byte[] binaryData;
      try {
        binaryData = 
          System.Convert.FromBase64CharArray(base64CharArray,
          0,
          base64CharArray.Length);
      }
      catch ( System.ArgumentNullException ) {
        //base 64 字符數(shù)組為null
        return
      }
      catch ( System.FormatException ) {
        //長(zhǎng)度錯(cuò)誤,無(wú)法整除4
        return
      }

      // 寫(xiě)輸出數(shù)據(jù)
      System.IO.FileStream outFile;
      try {
        outFile = new System.IO.FileStream(sOutputFilename,
          System.IO.FileMode.Create,
          System.IO.FileAccess.Write);
        outFile.Write(binaryData, 0, binaryData.Length);
        outFile.Close();
      }
      catch{// (System.Exception exp) {
        //流錯(cuò)誤
      }

    }

    /**//// <summary>
    /// 編碼文件
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <param name="sOutputFilename">輸出文件</param>
    public void EncryptFile(string sInputFilename,string sOutputFilename){

      System.IO.FileStream inFile;     
      byte[]                 binaryData;

      try {
        inFile = new System.IO.FileStream(sInputFilename,
          System.IO.FileMode.Open,
          System.IO.FileAccess.Read);
        binaryData = new Byte[inFile.Length];
        long bytesRead = inFile.Read(binaryData, 0,
          (int) inFile.Length);
        inFile.Close();
      }
      catch { //(System.Exception exp) {
        return
      }

      // 轉(zhuǎn)換二進(jìn)制輸入為Base64 UUEncoded輸出
      // 每3個(gè)字節(jié)在源數(shù)據(jù)里作為4個(gè)字節(jié) 
      long arrayLength = (long) ((4.0d/3.0d) * binaryData.Length);
    
      // 如果無(wú)法整除4
      if (arrayLength % 4 != 0) {
        arrayLength += 4 - arrayLength % 4
      }
    
      char[] base64CharArray = new char[arrayLength];
      try {
        System.Convert.ToBase64CharArray(binaryData, 
          0,
          binaryData.Length,
          base64CharArray,
          0);
      }
      catch (System.ArgumentNullException) {
        //二進(jìn)制數(shù)組為NULL.
        return
      }
      catch (System.ArgumentOutOfRangeException) {
        //長(zhǎng)度不夠
        return
      }

      // 寫(xiě)UUEncoded數(shù)據(jù)到文件內(nèi)
      System.IO.StreamWriter outFile; 
      try {
        outFile = new System.IO.StreamWriter(sOutputFilename,
          false,
          System.Text.Encoding.ASCII);             
        outFile.Write(base64CharArray);
        outFile.Close();
      }
      catch{// (System.Exception exp) {
        //文件流出錯(cuò)
      }
 

    }
  }
  /**//// <summary>
  /// DES 加密
  /// 支持Key(鑰匙)加密變化
  /// 支持還原
  /// 
  /// 演示操作:
  ///  // 64位,8個(gè)字節(jié)
  ///  string sSecretKey;
  ///
  ///  // 獲取Key
  ///  sSecretKey = GenerateKey();
  ///
  ///  // 托管
  ///  GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
  ///
  ///  // 加密文件
  ///  EncryptFile(@"C:\MyData.txt",
  ///  @"C:\Encrypted.txt",
  ///  sSecretKey);
  ///
  ///  // 解密文件
  ///  DecryptFile(@"C:\Encrypted.txt",
  ///  @"C:\Decrypted.txt",
  ///  sSecretKey);
  ///
  ///  // 釋放托管內(nèi)容
  ///  ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
  ///  gch.Free();
  /// </summary>
  public class DES {
    [DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
    public static extern bool ZeroMemory(IntPtr Destination, int Length);

    public DES() {
      //
      // TODO: 在此處添加構(gòu)造函數(shù)邏輯
      //
    }

    /**//// <summary>
    /// 創(chuàng)建Key
    /// </summary>
    /// <returns></returns>
    public string GenerateKey() {
      // 創(chuàng)建一個(gè)DES 算法的實(shí)例。自動(dòng)產(chǎn)生Key
      DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

      // 返回自動(dòng)創(chuàng)建的Key 用于加密
      return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
    }

    /**//// <summary>
    /// 加密字符串
    /// </summary>
    /// <param name="sInputString">輸入字符</param>
    /// <param name="sKey">Key</param>
    /// <returns>加密結(jié)果</returns>
    public string EncryptString(string sInputString,string sKey){
      byte[] data = Encoding.Default.GetBytes(sInputString);
      byte[] result;
      DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
      DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
      DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
      ICryptoTransform desencrypt = DES.CreateEncryptor();
      result = desencrypt.TransformFinalBlock(data,0,data.Length);

      string desString = ""
      for(int i=0i<result.Length;i++){
        desString += result[i].ToString() + "-"
      }
      
      //return desString.TrimEnd('-');
      return BitConverter.ToString(result);
    }

    /**//// <summary>
    /// 解密字符串
    /// </summary>
    /// <param name="sInputString">輸入字符</param>
    /// <param name="sKey">Key</param>
    /// <returns>解密結(jié)果</returns>
    public string DecryptString(string sInputString,string sKey){
      string[] sInput = sInputString.Split("-".ToCharArray());
      byte[] data = new byte[sInput.Length];
      byte[] result;
      for(int i=0i<sInput.Length;i++)
        data[i] = byte.Parse(sInput[i],System.Globalization.NumberStyles.HexNumber);

      DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
      DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
      DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
      ICryptoTransform desencrypt = DES.CreateDecryptor();
      result = desencrypt.TransformFinalBlock(data,0,data.Length);
      return Encoding.Default.GetString(result);
    }

    /**//// <summary>
    /// 加密文件
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <param name="sOutputFilename">輸出文件</param>
    /// <param name="sKey">Key</param>
    public void EncryptFile(string sInputFilename,
      string sOutputFilename,
      string sKey) {
      FileStream fsInput = new FileStream(sInputFilename,
        FileMode.Open,
        FileAccess.Read);

      FileStream fsEncrypted = new FileStream(sOutputFilename,
        FileMode.Create,
        FileAccess.Write);
      DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
      DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
      DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
      ICryptoTransform desencrypt = DES.CreateEncryptor();
      CryptoStream cryptostream = new CryptoStream(fsEncrypted,
        desencrypt,
        CryptoStreamMode.Write);

      byte[] bytearrayinput = new byte[fsInput.Length];
      fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
      cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
      cryptostream.Close();
      fsInput.Close();
      fsEncrypted.Close();
    }

    /**//// <summary>
    /// 解密文件
    /// </summary>
    /// <param name="sInputFilename">輸入文件</param>
    /// <param name="sOutputFilename">輸出文件</param>
    /// <param name="sKey">Key</param>
    public void DecryptFile(string sInputFilename,
      string sOutputFilename,
      string sKey) {
      DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
      DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
      DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

      FileStream fsread = new FileStream(sInputFilename,
        FileMode.Open,
        FileAccess.Read);
      ICryptoTransform desdecrypt = DES.CreateDecryptor();
      CryptoStream cryptostreamDecr = new CryptoStream(fsread,
        desdecrypt,
        CryptoStreamMode.Read);
      StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
      fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
      fsDecrypted.Flush();
      fsDecrypted.Close();
    }

  }
}
關(guān)鍵詞:C#