You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. using System.Security.Cryptography;
  8. namespace ManagementSystem.Library
  9. {
  10. class UtilityClass
  11. {
  12. #region 加解密相關
  13. /// <summary>
  14. /// 進行DES加密
  15. /// </summary>
  16. /// <param name="pToEncrypt">要加密的字串</param>
  17. /// <param name="key">金鑰,必須為8位</param>
  18. /// <returns>以Base64格式返回的加密字串</returns>
  19. public static string EncryptDES(string pToEncrypt, string sKey)
  20. {
  21. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
  22. {
  23. byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
  24. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  25. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  26. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  27. using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
  28. {
  29. cs.Write(inputByteArray, 0, inputByteArray.Length);
  30. cs.FlushFinalBlock();
  31. cs.Close();
  32. }
  33. string str = Convert.ToBase64String(ms.ToArray());
  34. ms.Close();
  35. return str;
  36. }
  37. }
  38. static string DecryptDES(string pToDecrypt, string sKey)
  39. {
  40. byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
  41. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
  42. {
  43. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  44. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  45. MemoryStream ms = new MemoryStream();
  46. using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
  47. {
  48. cs.Write(inputByteArray, 0, inputByteArray.Length);
  49. cs.FlushFinalBlock();
  50. cs.Close();
  51. }
  52. string str = Encoding.UTF8.GetString(ms.ToArray());
  53. ms.Close();
  54. return str;
  55. }
  56. }
  57. static string EncryptDES(int pToEncrypt, string sKey)
  58. {
  59. return EncryptDES(pToEncrypt.ToString(), sKey);
  60. }
  61. #endregion
  62. }
  63. }