using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Security.Cryptography; namespace ManagementSystem.Library { class UtilityClass { #region 加解密相關 /// /// 進行DES加密 /// /// 要加密的字串 /// 金鑰,必須為8位 /// 以Base64格式返回的加密字串 public static string EncryptDES(string pToEncrypt, string sKey) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return str; } } static string DecryptDES(string pToDecrypt, string sKey) { byte[] inputByteArray = Convert.FromBase64String(pToDecrypt); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } static string EncryptDES(int pToEncrypt, string sKey) { return EncryptDES(pToEncrypt.ToString(), sKey); } #endregion } }