注:由於加密、解密字符串時,需要用到加密類和內存流,所以首先需要在命名空間區域添加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(); }