class DESHelper { string _iv = "9AUP"; string _key = "9d"; /// <summary> /// DES加密偏移量,必須是>=8位長的字符串 /// </summary> public string Iv { get { return _iv; } set { _iv = value; } } /// <summary> /// DES加密的私鑰,必須是8位長的字符串 /// </summary> public string Key { get { return _key; } set { _key = value; } } /// <summary> /// 對字符串進行DES加密 /// </summary> /// <param name="sourceString">待加密的字符串</param> /// <returns>加密後的BASE64編碼的字符串</returns> public string Encrypt(string sourceString) { byte[] btKey = Encoding.Default.GetBytes(_key); byte[] btIv = Encoding.Default.GetBytes(_iv); var des = new DESCryptoServiceProvider(); using (var ms = new MemoryStream()) { byte[] inData = Encoding.Default.GetBytes(sourceString); try { using (var cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { throw ex; } } } /// <summary> /// 對DES加密後的字符串進行解密 /// </summary> /// <param name="encryptedString">待解密的字符串</param> /// <returns>解密後的字符串</returns> public string Decrypt(string encryptedString) { byte[] btKey = Encoding.Default.GetBytes(_key); byte[] btIv = Encoding.Default.GetBytes(_iv); var des = new DESCryptoServiceProvider(); using (var ms = new MemoryStream()) { try { byte[] inData = Convert.FromBase64String(encryptedString); using (var cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Encoding.Default.GetString(ms.ToArray()); } catch (Exception ex) { throw ex; } } } }