当前位置:编程学习 > 网站相关 >>

c#MD5加密和解密

  1. using System.Security.Cryptography;   
  2. using    System.IO;     
  3. using    System.Text;   
  4.   
  5. ///MD5加密   
  6.   public string MD5Encrypt(string    pToEncrypt,  string    sKey)   
  7.     {     
  8.      DESCryptoServiceProvider    des  =  new    DESCryptoServiceProvider();     
  9.    byte[]    inputByteArray  =    Encoding.Default.GetBytes(pToEncrypt);     
  10.      des.Key  =    ASCIIEncoding.ASCII.GetBytes(sKey);     
  11.      des.IV  =    ASCIIEncoding.ASCII.GetBytes(sKey);     
  12.      MemoryStream    ms  =  new    MemoryStream();     
  13.      CryptoStream    cs  =  new    CryptoStream(ms,    des.CreateEncryptor(),CryptoStreamMode.Write);     
  14.      cs.Write(inputByteArray,  0,    inputByteArray.Length);     
  15.      cs.FlushFinalBlock();     
  16.      StringBuilder    ret  =  new    StringBuilder();     
  17.    foreach(byte    b  in    ms.ToArray())     
  18.      {     
  19.       ret.AppendFormat("{0:X2}",    b);     
  20.      }     
  21.      ret.ToString();     
  22.    return    ret.ToString();     
  23.   
  24.   
  25.     }   
  26.   
  27.   ///MD5解密   
  28.   public string MD5Decrypt(string    pToDecrypt,  string    sKey)   
  29.     {   
  30.      DESCryptoServiceProvider    des  =  new    DESCryptoServiceProvider();     
  31.   
  32.    byte[]    inputByteArray  =  new  byte[pToDecrypt.Length  /  2];     
  33.    for(int    x  =  0;    x  <    pToDecrypt.Length  /  2;    x++)     
  34.      {     
  35.     int    i  =    (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));     
  36.       inputByteArray[x]  =    (byte)i;     
  37.      }     
  38.   
  39.      des.Key  =    ASCIIEncoding.ASCII.GetBytes(sKey);     
  40.      des.IV  =    ASCIIEncoding.ASCII.GetBytes(sKey);     
  41.      MemoryStream    ms  =  new    MemoryStream();     
  42.      CryptoStream    cs  =  new    CryptoStream(ms,    des.CreateDecryptor(),CryptoStreamMode.Write);     
  43.      cs.Write(inputByteArray,  0,    inputByteArray.Length);     
  44.      cs.FlushFinalBlock();     
  45.   
  46.      StringBuilder    ret  =  new    StringBuilder();     
  47.                 
  48.    return    System.Text.Encoding.Default.GetString(ms.ToArray());     
  49.     }  
 
C#代码
补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,