EncryptionTool.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using UnityEngine;
  8. public static class EncryptionTool
  9. {
  10. public static byte[] MakeMD5(byte[] kb)
  11. {
  12. MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();//用来给密钥进行散列
  13. byte[] keyhash = md5.ComputeHash(kb);//给密钥散列
  14. md5.Clear();//释放资源
  15. return keyhash;
  16. }
  17. #region 加密
  18. /// <summary>
  19. /// 使用给定密钥加密字符串
  20. /// </summary>
  21. /// <param name="original">明文</param>
  22. /// <param name="key">密钥</param>
  23. /// <returns>加密后的密文</returns>
  24. public static string Encrypt(this string original, string key)
  25. {
  26. byte[] buff = Encoding.Unicode.GetBytes(original);//把明文转化成二进制数组
  27. byte[] kb = Encoding.Unicode.GetBytes(key);//把密钥转化成二进制数组
  28. TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();//用TripleDES算法来加密的类
  29. des.Key = MakeMD5(kb);//设置TripleDES算法的密钥
  30. des.Mode = CipherMode.ECB;//设置算法的模式
  31. byte[] enByte = des.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length);
  32. return Convert.ToBase64String(enByte);
  33. }
  34. /// <summary>
  35. /// 使用默认密钥加密
  36. /// </summary>
  37. /// <param name="original">明文</param>
  38. /// <returns>加密后的密文</returns>
  39. public static string Encrypt(this string original)
  40. {
  41. return Encrypt(original, "ldq");
  42. }
  43. #endregion
  44. #region 解密
  45. /// <summary>
  46. /// 使用指定的密钥解密
  47. /// </summary>
  48. /// <param name="encrypted">加密过后的密码</param>
  49. /// <param name="key">密钥(密钥的明文)</param>
  50. /// <returns>密码对应的明文</returns>
  51. public static string Decrypt(this string encrypted, string key)
  52. {
  53. byte[] buff = Convert.FromBase64String(encrypted);
  54. byte[] kb = Encoding.Unicode.GetBytes(key);
  55. TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
  56. des.Key = MakeMD5(kb);
  57. des.Mode = CipherMode.ECB;
  58. byte[] original = des.CreateDecryptor().TransformFinalBlock(buff, 0, buff.Length);//获取明文的byte数组
  59. return Encoding.Unicode.GetString(original);//转化成字符串,并返回
  60. }
  61. public static string Decrypt(this string encrypted)
  62. {
  63. return Decrypt(encrypted, "ldq");
  64. }
  65. #endregion
  66. }