dd设计应用程序时,为了防止一些敏感信息的泄露,通常需要对这些信息进行加密。以用户的登录密码为例,如果密码以明文的形式存储在数据表中,很容易就会被人发现;相反,如果密码以密文的形式储存,即使别人从数据表中发现了密码,也是加密之后的密码,根本不能使用。通过对密码进行加密,能够极大地提高系统的保密性。下面通过一个实例讲解如何对字符串进行加密与解密。
创建一个控制台应用程序,命名为EDString。在该程序中定义一个静态的字符串变量,用来记录加密密钥。代码如下:
InBlock.gifstatic string encryptKey = "Oyea";        
InBlock.gif//定义密钥
自定义一个返回值类型为string类型的Encrypt方法,用来对字符串进行加密。该方法中有一个string类型的参数,用来表示要加密的字符串。Encrypt方法实现代码如下:
InBlock.gif加密字符串    #region 加密字符串    
/// <summary>
/// 加密字符串    
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
InBlock.gifstatic string Encrypt(string str)    
InBlock.gif{    
InBlock.gif        DESCryptoServiceProvider descsp = new
InBlock.gifDESCryptoServiceProvider();     //实例化加/解密类对象    
InBlock.gif        byte[] key = Encoding.Unicode.GetBytes(encryptKey);
InBlock.gif//定义字节数组,用来存储密钥    
InBlock.gif        byte[] data = Encoding.Unicode.GetBytes(str);
InBlock.gif//定义字节数组,用来存储要加密的字符串    
InBlock.gif        MemoryStream MStream = new MemoryStream();
InBlock.gif//实例化内存流对象    
InBlock.gif        //使用内存流实例化加密流对象    
InBlock.gif        CryptoStream CStream = new CryptoStream
InBlock.gif(MStream, descsp.CreateEncryptor(key, key),
InBlock.gifCryptoStreamMode.Write);    
InBlock.gif        CStream.Write(data, 0, data.Length);    
InBlock.gif//向加密流中写入数据    
InBlock.gif        CStream.FlushFinalBlock();                            
InBlock.gif//释放加密流    
InBlock.gif        return Convert.ToBase64String(MStream.ToArray());
InBlock.gif//返回加密后的字符串    
InBlock.gif}    
InBlock.gif#endregion
说明:由于加密、解密字符串时,需要用到加密类和内存流,所以首先需要在命名空间区域添加System.Security.Cryptography和System.IO命名空间。
自定义一个返回值类型为string类型的Decrypt方法,用来对加密后的字符串进行解密。该方法中有一个string类型的参数,用来表示要解密的字符串。Decrypt方法实现代码如下
InBlock.gif解密字符串    #region 解密字符串    
/// <summary>
/// 解密字符串    
/// </summary>
/// <param name="str">要解密的字符串</param>
/// <returns>解密后的字符串</returns>
InBlock.gifstatic string Decrypt(string str)    
InBlock.gif{    
InBlock.gif        DESCryptoServiceProvider descsp = new
InBlock.gif DESCryptoServiceProvider();     //实例化加/解密类对象    
InBlock.gif        byte[] key = Encoding.Unicode.GetBytes(encryptKey);
InBlock.gif//定义字节数组,用来存储密钥    
InBlock.gif        byte[] data = Convert.FromBase64String(str);
InBlock.gif//定义字节数组,用来存储要解密的字符串    
InBlock.gif        MemoryStream MStream = new MemoryStream();
InBlock.gif//实例化内存流对象    
InBlock.gif        //使用内存流实例化解密流对象    
InBlock.gif        CryptoStream CStream = new CryptoStream(MStream,
InBlock.gifdescsp.CreateDecryptor(key, key), CryptoStreamMode.Write);    
InBlock.gif        CStream.Write(data, 0, data.Length);            
InBlock.gif//向解密流中写入数据    
InBlock.gif        CStream.FlushFinalBlock();                            
InBlock.gif//释放解密流    
InBlock.gif        return Encoding.Unicode.GetString
InBlock.gif(MStream.ToArray());             //返回解密后的字符串    
InBlock.gif}    
InBlock.gif#endregion