对称可逆加密Des
加密后能解密回原文,但是需要一个key
加密key与解密key是一样的(对称)
但是key的安全性问题一定要得到保证
code:
//key可以写在配置文件中 //加密key static string key = "A1B2C3D4E5"; private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(key.Substring(0, 8)); //解密key private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(key.Insert(0, "w").Substring(0, 8)); /// <summary> /// DES加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public async Task<string> Encrypt(string str) { var dsp = new DESCryptoServiceProvider(); //创建一个流对象 using (MemoryStream stream = new MemoryStream()) { //将数据写入流中 CryptoStream cryptoStream = new CryptoStream(stream, dsp.CreateEncryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write); StreamWriter streamWriter = new StreamWriter(cryptoStream); streamWriter.Write(str); streamWriter.Flush(); cryptoStream.FlushFinalBlock(); stream.Flush(); return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length); } } /// <summary> /// DES解密 /// </summary> /// <param name="str"></param> /// <returns></returns> public async Task<string> Decrypt(string str) { var dsp = new DESCryptoServiceProvider(); byte[] buffer = Convert.FromBase64String(str); using (MemoryStream stream = new MemoryStream()) { CryptoStream cryptoStream = new CryptoStream(stream, dsp.CreateEncryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write); cryptoStream.Write(buffer, 0, buffer.Length); cryptoStream.FlushFinalBlock(); return Encoding.UTF8.GetString(stream.ToArray()); } }