加密 public static string Encrypt(string sourceString, string key, string iv) { try { byte[] btKey = Encoding.UTF8.GetBytes(key); byte[] btIV = Encoding.UTF8.GetBytes(iv); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream()) { byte[] inData = Encoding.UTF8.GetBytes(sourceString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Convert.ToBase64String(ms.ToArray()); } catch { return sourceString; } } } catch { } return "DES加密出错"; } 调用: string recordString = Encrypt("金胖子死了", "20111219", "12345678"); 结果:recordString= "xQ969nexy964SXhkTuekUQ=="
解密
public static string Decrypt(string encryptedString, string key, string iv) { byte[] btKey = Encoding.UTF8.GetBytes(key); byte[] btIV = Encoding.UTF8.GetBytes(iv); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream()) { byte[] inData = Convert.FromBase64String(encryptedString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Encoding.UTF8.GetString(ms.ToArray()); } catch { return encryptedString; } } } 调用:string recordString = DESOperation.Decrypt("xQ969nexy964SXhkTuekUQ==", "20111219", "12345678"); 结果:recordString = “金胖子死了”;