CmdEncryptGlobalMetadata.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.IO;
  3. using UnityEditor;
  4. namespace XGame.Editor.Build
  5. {
  6. [BuildCommand((uint)BuildCommandPriority.EncryptGlobalMetadata)]
  7. class CmdEncryptGlobalMetadata : BaseBuildCommand, ICommandExecuter
  8. {
  9. const string EncryptKey = @"DMMDyUKYp7z3orgK/bIImLojiy6/t3PUjIe6lojNGQVFB59AzSCRz7V7uSMI6DD2+";
  10. const int Encryptoffset = 8;
  11. const int EncryptLength = 1024;
  12. public BuildErrorCode Execute()
  13. {
  14. BuildErrorCode rc = BuildErrorCode.CmdCompleted;
  15. if (Context.config.scriptImpl == ScriptingImplementation.IL2CPP)
  16. {
  17. string globalMetadata = GetMetadataPath(Context.config.target);
  18. try
  19. {
  20. BuildLog.Log($"CmdEncriptGlobalMetadata Encrypt: {globalMetadata}, Exists: {File.Exists(globalMetadata)}");
  21. var bytes = File.ReadAllBytes(globalMetadata);
  22. Encrypt(bytes);
  23. File.WriteAllBytes(globalMetadata, bytes);
  24. }
  25. catch (Exception e)
  26. {
  27. BuildLog.Error($"CmdEncriptGlobalMetadata failed! Error: {e.Message}\nStackTrace: {e.StackTrace}");
  28. rc = BuildErrorCode.EncryptGlobalMetadataError;
  29. }
  30. }
  31. return rc;
  32. }
  33. string GetMetadataPath(BuildTarget target)
  34. {
  35. string productName = Context.config.project.productName;
  36. const string relative = "Data/Managed/Metadata/global-metadata.dat";
  37. return target switch
  38. {
  39. BuildTarget.Android => Path.Combine(Context.appOutputPath, "unityLibrary/src/main/assets/bin", relative),
  40. BuildTarget.iOS => Path.Combine(Context.appOutputPath, relative),
  41. BuildTarget.StandaloneWindows => Path.Combine(Directory.GetParent(Context.appOutputPath).ToString(), $"{productName}_Data/il2cpp_data/Metadata/global-metadata.dat"),
  42. BuildTarget.StandaloneWindows64 => Path.Combine(Directory.GetParent(Context.appOutputPath).ToString(), $"{productName}_Data/il2cpp_data/Metadata/global-metadata.dat"),
  43. _ => throw new NotImplementedException($"GetMetadataPath fail. target: {target}")
  44. };
  45. }
  46. void Encrypt(byte[] bytes)
  47. {
  48. var keybuffer = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
  49. var len = keybuffer.Length;
  50. for (int i = Encryptoffset; i < EncryptLength; i++)
  51. bytes[i] ^= keybuffer[(i - Encryptoffset) % len];
  52. }
  53. }
  54. }