C# 字符串的加密与解密
string EncryptKey = "yeah";//定义密钥 /// <summary> /// 字符串加密 /// </summary> /// <param name="str">要加密的字符串</param> /// <returns></returns> private string Encrypt(string str) { DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密解密对象 byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组、用来存储密钥 byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组、用来存储要解密的字符串 MemoryStream mstream = new MemoryStream();//实例化内存流对象 //使用内存流实例化加密流对象 CryptoStream cstream = new CryptoStream(mstream, desc.CreateEncryptor(key, key), CryptoStreamMode.Write); cstream.Write(data, 0, data.Length);//想加密流中写入数据 cstream.FlushFinalBlock();//释放加密流 return Convert.ToBase64String(mstream.ToArray());//返回加密后的字符串 } /// <summary> /// 字符串解密 /// </summary> /// <param name="str">要解密的字符串</param> /// <returns></returns> private string Decrypt(string str) { DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密、解密对象 byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组用来存储密钥 byte[] data = Convert.ToBase64String(str);//定义字节数组用来存储密钥 MemoryStream mstream = new MemoryStream();//实例化内存流对象 //使用内存流实例化解密对象 CryptoStream cstream = new CryptoStream(mstream, desc.CreateDecryptor(key, key), CryptoStreamMode.Write); cstream.Write(data, 0, data.Length);//向解密流中写入数据 cstream.FlushFinalBlock();//释放解密流 return Encoding.Unicode.GetString(mstream.ToArray()); }