标签:
注:由于加密、解密字符串时,需要用到加密类和内存流,所以首先需要在命名空间区域添加System.Security.Cryptography和System.IO命名空间。 //自定义的加密字符串 static string encryptKey = "1234"; //字符串加密 static string Encrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); byte[] key = Encoding.Unicode.GetBytes(encryptKey); byte[] data = Encoding.Unicode.GetBytes(str); MemoryStream MStream = new MemoryStream(); CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); CStream.FlushFinalBlock(); return Convert.ToBase64String(MStream.ToArray()); } //字符串解密 static string Decrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); byte[] key = Encoding.Unicode.GetBytes(encryptKey); byte[] data = Convert.FromBase64String(str); MemoryStream MStream = new MemoryStream(); CryptoStream CStram = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write); CStram.Write(data, 0, data.Length); CStram.FlushFinalBlock(); return Encoding.Unicode.GetString(MStream.ToArray()); } //调用方法 static void Main(string[] args) { Console.Write("请输入要加密的字符串:"); Console.WriteLine(); string strOld = Console.ReadLine(); string strNew = Encrypt(strOld); Console.WriteLine("加密后的字符串:" + strNew); Console.WriteLine("解密后的字符串:" + Decrypt(strNew)); Console.ReadLine(); }
标签:
原文地址:http://www.cnblogs.com/zhangqian976431/p/5728540.html