EncryptHelper.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections;
  2. using System.IO;
  3. using ET;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. namespace VEngine
  7. {
  8. public class EncryptHelper
  9. {
  10. public static string resKey;
  11. private static char[] _resKeyChars;
  12. public static char[] resKeyChars
  13. {
  14. get
  15. {
  16. if(_resKeyChars == null && !string.IsNullOrEmpty(resKey))
  17. {
  18. _resKeyChars = resKey.ToCharArray();
  19. }
  20. return _resKeyChars;
  21. }
  22. }
  23. /// <summary>
  24. /// 创建加密过的数据
  25. /// </summary>
  26. public static byte[] CreateEncryptData(string filePath, string secretKey)
  27. {
  28. byte[] encryptData;
  29. char[] key = secretKey.ToCharArray();
  30. using (FileStream fs = new FileStream(filePath, FileMode.Open))
  31. {
  32. encryptData = new byte[fs.Length];
  33. fs.Read(encryptData, 0, encryptData.Length);
  34. for (int i = 0; i < encryptData.Length; i++)
  35. {
  36. encryptData[i] = (byte)(encryptData[i] ^ key[i % key.Length]);
  37. }
  38. }
  39. return encryptData;
  40. }
  41. /// <summary>
  42. /// 获取解密的数据(无密钥的情况下直接获取数据)
  43. /// </summary>
  44. internal static byte[] GetDecryptData(string filePath, char[] secretKey = null)
  45. {
  46. byte[] encryptData;
  47. using (UnityWebRequest webRequest = UnityWebRequest.Get(filePath))
  48. {
  49. webRequest.SendWebRequest();
  50. while (!webRequest.isDone) { }
  51. #if UNITY_2020_1_OR_NEWER
  52. if (webRequest.result == UnityWebRequest.Result.Success)
  53. #else
  54. if (string.IsNullOrEmpty(webRequest.error))
  55. #endif
  56. {
  57. encryptData = webRequest.downloadHandler.data;
  58. if (secretKey != null)
  59. {
  60. for (int i = 0; i < encryptData.Length; i++)
  61. {
  62. encryptData[i] = (byte)(encryptData[i] ^ secretKey[i % secretKey.Length]);
  63. }
  64. }
  65. }
  66. else
  67. {
  68. encryptData = null;
  69. }
  70. }
  71. return encryptData;
  72. }
  73. }
  74. }