2
0

EncryptResourcesTask.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.IO.Compression;
  2. using System.Security.Cryptography;
  3. using Microsoft.Build.Framework;
  4. namespace PixiEditor.Api.CGlueMSBuild;
  5. public class EncryptResourcesTask : Microsoft.Build.Utilities.Task
  6. {
  7. [Required] public string ResourcesPath { get; set; }
  8. [Required] public string IntermediateOutputPath { get; set; } = string.Empty;
  9. [Required] public string OutputPath { get; set; } = string.Empty;
  10. [Output] public string EncryptionKey { get; set; } = string.Empty;
  11. [Output] public string EncryptionIv { get; set; } = string.Empty;
  12. public override bool Execute()
  13. {
  14. try
  15. {
  16. if (!Directory.Exists(ResourcesPath))
  17. {
  18. Log.LogError($"Resources directory does not exist: {ResourcesPath}");
  19. return false;
  20. }
  21. string[] files = Directory.GetFiles(ResourcesPath, "*.*", SearchOption.AllDirectories);
  22. if (files.Length == 0)
  23. {
  24. return true;
  25. }
  26. string path = Path.Combine(IntermediateOutputPath, "resources.zip");
  27. if (File.Exists(path))
  28. {
  29. File.Delete(path);
  30. }
  31. ZipFile.CreateFromDirectory(ResourcesPath, path,
  32. CompressionLevel.Fastest, false);
  33. byte[] data = File.ReadAllBytes(Path.Combine(IntermediateOutputPath, "resources.zip"));
  34. byte[] encryptionKey = new byte[128 / 8];
  35. byte[] iv = new byte[128 / 8];
  36. if (EncryptionKey == string.Empty)
  37. {
  38. RandomNumberGenerator.Create().GetBytes(encryptionKey);
  39. EncryptionKey = Convert.ToBase64String(encryptionKey);
  40. }
  41. if (EncryptionIv == string.Empty)
  42. {
  43. RandomNumberGenerator.Create().GetBytes(iv);
  44. EncryptionIv = Convert.ToBase64String(iv);
  45. }
  46. byte[] encryptedData = Encrypt(data, encryptionKey, iv);
  47. File.WriteAllBytes(Path.Combine(OutputPath, "resources.data"), encryptedData);
  48. return true;
  49. }
  50. catch (Exception ex)
  51. {
  52. Log.LogErrorFromException(ex);
  53. return false;
  54. }
  55. }
  56. public byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
  57. {
  58. using var aes = Aes.Create();
  59. aes.KeySize = 128;
  60. aes.BlockSize = 128;
  61. aes.Padding = PaddingMode.Zeros;
  62. aes.Key = key;
  63. aes.IV = iv;
  64. using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
  65. {
  66. return PerformCryptography(data, encryptor);
  67. }
  68. }
  69. private byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
  70. {
  71. using (var ms = new MemoryStream())
  72. using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
  73. {
  74. cryptoStream.Write(data, 0, data.Length);
  75. cryptoStream.FlushFinalBlock();
  76. return ms.ToArray();
  77. }
  78. }
  79. }