EncryptHelper.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 < key.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. //Logger.I($"GetDecryptData filePath : {filePath} secretKey : {secretKey}");
  47. byte[] encryptData;
  48. if (filePath.IndexOf("storage/emulated") > 0)
  49. {
  50. encryptData = File.ReadAllBytes(filePath);
  51. if (secretKey != null)
  52. {
  53. for (int i = 0; i < secretKey.Length; i++)
  54. {
  55. encryptData[i] = (byte)(encryptData[i] ^ secretKey[i % secretKey.Length]);
  56. }
  57. }
  58. }
  59. else
  60. {
  61. using (UnityWebRequest webRequest = UnityWebRequest.Get(filePath))
  62. {
  63. webRequest.SendWebRequest();
  64. while (!webRequest.isDone) { }
  65. #if UNITY_2020_1_OR_NEWER
  66. //Logger.I($"GetDecryptData filePath : 1 webRequest.isDone : {webRequest.isDone} webRequest.result : {webRequest.result}");
  67. if (webRequest.result == UnityWebRequest.Result.Success)
  68. #else
  69. Logger.I($"GetDecryptData filePath : 2");
  70. if (string.IsNullOrEmpty(webRequest.error))
  71. #endif
  72. {
  73. //Logger.I($"GetDecryptData filePath : 3");
  74. encryptData = webRequest.downloadHandler.data;
  75. if (secretKey != null)
  76. {
  77. for (int i = 0; i < secretKey.Length; i++)
  78. {
  79. encryptData[i] = (byte)(encryptData[i] ^ secretKey[i % secretKey.Length]);
  80. }
  81. }
  82. }
  83. else
  84. {
  85. //Logger.I($"GetDecryptData filePath : 4");
  86. encryptData = null;
  87. }
  88. }
  89. }
  90. return encryptData;
  91. }
  92. }
  93. }