.NET加密技术应用

  1 using System;
  2 using System.Text;
  3 using System.Security;
  4 using System.Security.Cryptography;
  5 using System.IO;
  6 namespace EncryptClasses
  7 {
  8  /// <summary>
  9  /// 此处定义的是DES加密,为了便于今后的管理和维护
 10  /// 请不要随便改动密码,或者改变了密码后请一定要
 11  /// 牢记先前的密码,否则将会照成不可预料的损失
 12  /// </summary>
 13  public class DESEncrypt
 14  {
 15   #region "member fields"
 16   private string iv="12345678";
 17   private string key="12345678";
 18   private Encoding encoding=new UnicodeEncoding();
 19   private DES des;
 20   #endregion
 21   /// <summary>
 22   /// 构造函数
 23   /// </summary>
 24   public DESEncrypt()
 25   {
 26    des=new DESCryptoServiceProvider();
 27   }
 28   #region "propertys"
 29   /// <summary>
 30   /// 设置加密密钥
 31   /// </summary>
 32   public string EncryptKey
 33   {
 34    get{return this.key;}
 35    set
 36    {
 37       this.key=value;
 38    }
 39   }
 40   /// <summary>
 41   /// 要加密字符的编码模式
 42   /// </summary>
 43   public Encoding EncodingMode
 44   {
 45    get{return this.encoding;}
 46    set{this.encoding=value;}
 47   }
 48   #endregion
 49   #region "methods"
 50   /// <summary>
 51   /// 加密字符串并返回加密后的结果
 52   /// </summary>
 53   /// <param name="str"></param>
 54   /// <returns></returns>
 55   public string EncryptString(string str)
 56   {
 57    byte[] ivb=Encoding.ASCII.GetBytes(this.iv);
 58    byte[] keyb=Encoding.ASCII.GetBytes(this.EncryptKey);//得到加密密钥
 59    byte[] toEncrypt=this.EncodingMode.GetBytes(str);//得到要加密的内容
 60    byte[] encrypted;
 61    ICryptoTransform encryptor=des.CreateEncryptor(keyb,ivb);
 62    MemoryStream msEncrypt=new MemoryStream();
 63    CryptoStream csEncrypt=new CryptoStream(msEncrypt,encryptor,CryptoStreamMode.Write);
 64    csEncrypt.Write(toEncrypt,0,toEncrypt.Length);
 65    csEncrypt.FlushFinalBlock();
 66    encrypted=msEncrypt.ToArray();
 67    csEncrypt.Close();
 68    msEncrypt.Close();
 69    return this.EncodingMode.GetString(encrypted);
 70   }
 71   /// <summary>
 72   /// 加密指定的文件,如果成功返回True,否则false
 73   /// </summary>
 74   /// <param name="filePath">要加密的文件路径</param>
 75   /// <param name="outPath">加密后的文件输出路径</param>
 76   public void EncryptFile(string filePath,string outPath)
 77   {
 78    bool isExist=File.Exists(filePath);
 79    if(isExist)//如果存在
 80    {
 81     byte[] ivb=Encoding.ASCII.GetBytes(this.iv);
 82     byte[] keyb=Encoding.ASCII.GetBytes(this.EncryptKey);
 83     //得到要加密文件的字节流
 84     FileStream fin=new FileStream(filePath,FileMode.Open,FileAccess.Read);
 85     StreamReader reader=new StreamReader(fin,this.EncodingMode);
 86     string dataStr=reader.ReadToEnd();
 87     byte[] toEncrypt=this.EncodingMode.GetBytes(dataStr);
 88     fin.Close();
 89 
 90     FileStream fout=new FileStream(outPath,FileMode.Create,FileAccess.Write);
 91     ICryptoTransform encryptor=des.CreateEncryptor(keyb,ivb);
 92     CryptoStream csEncrypt=new CryptoStream(fout,encryptor,CryptoStreamMode.Write);
 93     try
 94     {
 95      //加密得到的文件字节流
 96      csEncrypt.Write(toEncrypt,0,toEncrypt.Length);
 97      csEncrypt.FlushFinalBlock();
 98     }
 99     catch(Exception err)
100     {
101      throw new ApplicationException(err.Message);
102     }
103     finally
104     {
105      try
106      {
107       fout.Close();
108       csEncrypt.Close();
109      }
110      catch
111      {
112       ;
113      }
114     }
115    }
116    else
117    {
118     throw new FileNotFoundException("没有找到指定的文件");
119    }
120   }
121   /// <summary>
122   /// 文件加密函数的重载版本,如果不指定输出路径,
123   /// 那么原来的文件将被加密后的文件覆盖
124   /// </summary>
125   /// <param name="filePath"></param>
126   public void EncryptFile(string filePath)
127   {
128    this.EncryptFile(filePath,filePath);
129   }
130   /// <summary>
131   /// 解密给定的字符串
132   /// </summary>
133   /// <param name="str">要解密的字符</param>
134   /// <returns></returns>
135   public string DecryptString(string str)
136   {
137    byte[] ivb=Encoding.ASCII.GetBytes(this.iv);
138    byte[] keyb=Encoding.ASCII.GetBytes(this.EncryptKey);
139    byte[] toDecrypt=this.EncodingMode.GetBytes(str);
140    byte[] deCrypted=new byte[toDecrypt.Length];
141    ICryptoTransform deCryptor=des.CreateDecryptor(keyb,ivb);
142    MemoryStream msDecrypt=new MemoryStream(toDecrypt);
143    CryptoStream csDecrypt=new CryptoStream(msDecrypt,deCryptor,CryptoStreamMode.Read);
144    try
145    {
146     csDecrypt.Read(deCrypted,0,deCrypted.Length);
147    }
148    catch(Exception err)
149    {
150     throw new ApplicationException(err.Message);
151    }
152    finally
153    {
154     try
155     {
156      msDecrypt.Close();
157      csDecrypt.Close();
158     }
159     catch{;}
160    }
161    return this.EncodingMode.GetString(deCrypted);
162   }
163   /// <summary>
164   /// 解密指定的文件
165   /// </summary>
166   /// <param name="filePath">要解密的文件路径</param>
167   /// <param name="outPath">解密后的文件输出路径</param>
168   public void DecryptFile(string filePath,string outPath)
169   {
170    bool isExist=File.Exists(filePath);
171    if(isExist)//如果存在
172    {
173     byte[] ivb=Encoding.ASCII.GetBytes(this.iv);
174     byte[] keyb=Encoding.ASCII.GetBytes(this.EncryptKey);
175     FileInfo file=new FileInfo(filePath);
176     byte[] deCrypted=new byte[file.Length];
177     //得到要解密文件的字节流
178     FileStream fin=new FileStream(filePath,FileMode.Open,FileAccess.Read);
179     //解密文件
180     try
181     {
182      ICryptoTransform decryptor=des.CreateDecryptor(keyb,ivb);
183      CryptoStream csDecrypt=new CryptoStream(fin,decryptor,CryptoStreamMode.Read);
184      csDecrypt.Read(deCrypted,0,deCrypted.Length);
185     }
186     catch(Exception err)
187     {
188      throw new ApplicationException(err.Message);
189     }
190     finally
191     {
192      try
193      {
194       fin.Close();
195      }
196      catch{;}
197     }
198     FileStream fout=new FileStream(outPath,FileMode.Create,FileAccess.Write);
199     fout.Write(deCrypted,0,deCrypted.Length);
200     fout.Close();
201    }
202    else
203    {
204     throw new FileNotFoundException("指定的解密文件没有找到");
205    }
206   }
207   /// <summary>
208   /// 解密文件的重载版本,如果没有给出解密后文件的输出路径,
209   /// 则解密后的文件将覆盖先前的文件
210   /// </summary>
211   /// <param name="filePath"></param>
212   public void DecryptFile(string filePath)
213   {
214    this.DecryptFile(filePath,filePath);
215   }
216   #endregion
217  }
218  /// <summary>
219  /// MD5加密类,注意经MD5加密过的信息是不能转换回原始数据的
220  /// ,请不要在用户敏感的信息中使用此加密技术,比如用户的密码,
221  /// 请尽量使用对称加密
222  /// </summary>
223  public class MD5Encrypt
224  {
225   private MD5 md5;
226   public MD5Encrypt()
227   {
228    md5=new MD5CryptoServiceProvider();
229   }
230   /// <summary>
231   /// 从字符串中获取散列值
232   /// </summary>
233   /// <param name="str">要计算散列值的字符串</param>
234   /// <returns></returns>
235   public string GetMD5FromString(string str)
236   {
237    byte[] toCompute=Encoding.Unicode.GetBytes(str);
238    byte[] hashed=md5.ComputeHash(toCompute,0,toCompute.Length);
239    return Encoding.ASCII.GetString(hashed);
240   }
241   /// <summary>
242   /// 根据文件来计算散列值
243   /// </summary>
244   /// <param name="filePath">要计算散列值的文件路径</param>
245   /// <returns></returns>
246   public string GetMD5FromFile(string filePath)
247   {
248    bool isExist=File.Exists(filePath);
249    if(isExist)//如果文件存在
250    {
251     FileStream stream=new FileStream(filePath,FileMode.Open,FileAccess.Read);
252     StreamReader reader=new StreamReader(stream,Encoding.Unicode);
253     string str=reader.ReadToEnd();
254     byte[] toHash=Encoding.Unicode.GetBytes(str);
255     byte[] hashed=md5.ComputeHash(toHash,0,toHash.Length);
256     stream.Close();
257     return Encoding.ASCII.GetString(hashed);
258    }
259    else//文件不存在
260    {
261     throw new FileNotFoundException("指定的文件没有找到");
262    }
263   }
264  }
265  /// <summary>
266  /// 用于数字签名的hash类
267  /// </summary>
268  public class MACTripleDESEncrypt
269  {
270   private MACTripleDES mact;
271   private string __key="ksn168ch";
272   private byte[] __data=null;
273   public MACTripleDESEncrypt()
274   {
275    mact=new MACTripleDES();
276   }
277   /// <summary>
278   /// 获取或设置用于数字签名的密钥
279   /// </summary>
280   public string Key
281   {
282    get{return this.__key;}
283    set
284    {
285     int keyLength=value.Length;
286     int[] keyAllowLengths=new int[]{8,16,24};
287     bool isRight=false;
288     foreach(int i in keyAllowLengths)
289     {
290      if(keyLength==keyAllowLengths[i])
291      {
292       isRight=true;
293       break;
294      }
295     }
296     if(!isRight)
297      throw new ApplicationException("用于数字签名的密钥长度必须是8,16,24值之一");
298     else
299      this.__key=value;
300    }
301   }
302   /// <summary>
303   /// 获取或设置用于数字签名的用户数据
304   /// </summary>
305   public byte[] Data
306   {
307    get{return this.__data;}
308    set{this.__data=value;}
309   }
310   /// <summary>
311   /// 得到签名后的hash值
312   /// </summary>
313   /// <returns></returns>
314   public string GetHashValue()
315   {
316    if(this.Data==null)
317     throw new NotSetSpecialPropertyException("没有设置要进行数字签名的用户"+
318                                          "数据(property:Data)");
319    byte[] key=Encoding.ASCII.GetBytes(this.Key);
320    this.mact.Key=key;
321    byte[] hash_b=this.mact.ComputeHash(this.mact.ComputeHash(this.Data));
322    return Encoding.ASCII.GetString(hash_b);
323   }
324  }
325 }

posted @ 2007-04-11 18:01  电工男  阅读(296)  评论(0编辑  收藏  举报