TextureDecryptor.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #region Using directives
  2. using System;
  3. using System.IO;
  4. using System.Xml;
  5. using System.Collections.Generic;
  6. using Eq2FileInfo = Everquest2.IO.FileInfo;
  7. using Eq2FileStream = Everquest2.IO.FileStream;
  8. #endregion
  9. namespace Eq2VpkTool
  10. {
  11. public class TextureDecryptor
  12. {
  13. public static byte[] Decrypt(Eq2FileInfo textureFile)
  14. {
  15. if (!Configuration.Instance.IsLoaded) return null;
  16. if (!CanDecrypt(textureFile)) return null;
  17. using (Eq2FileStream stream = textureFile.OpenRead())
  18. {
  19. // Read encrypted data
  20. byte[] data = new byte[stream.Length];
  21. stream.Read(data, 0, (int)stream.Length);
  22. string key = GetDecryptionKey(textureFile);
  23. Decrypt(data, key);
  24. return data;
  25. }
  26. }
  27. public static bool CanDecrypt(Eq2FileInfo textureFile)
  28. {
  29. return GetDecryptionKey(textureFile) != null;
  30. }
  31. private static string GetDecryptionKey(Eq2FileInfo textureFile)
  32. {
  33. return Configuration.Instance.GetValue("/configuration/encrypted-maps/map[name=\"" + textureFile.FullName + "\"]/decryption-key");
  34. }
  35. private static void Decrypt(byte[] data, string key)
  36. {
  37. string[] bytes = key.Split(' ');
  38. if (bytes.Length != 8) return;
  39. byte[] baseKey = new byte[8];
  40. for (int i = 0; i < 8; ++i)
  41. {
  42. baseKey[i] = byte.Parse(bytes[i], System.Globalization.NumberStyles.HexNumber);
  43. }
  44. byte[] decryptionKey = CreateDecryptionKey(baseKey);
  45. Decrypt(data, decryptionKey);
  46. }
  47. private static byte[] CreateDecryptionKey(byte[] baseKey)
  48. {
  49. byte[] key = new byte[256];
  50. for (int i = 0; i < 256; ++i) key[i] = (byte)i;
  51. byte b = 0;
  52. for (int i = 0; i < 256; ++i)
  53. {
  54. byte k = key[(byte)i];
  55. b += (byte)(baseKey[i & 7] + k);
  56. key[i] = key[b];
  57. key[b] = k;
  58. }
  59. return key;
  60. }
  61. private static void Decrypt(byte[] data, byte[] key)
  62. {
  63. byte[] localKey = key.Clone() as byte[];
  64. byte b = 0;
  65. for (int i = 0; i < data.Length; ++i)
  66. {
  67. byte j = (byte)(i + 1);
  68. byte k = localKey[j];
  69. b += k;
  70. localKey[j] = localKey[b];
  71. localKey[b] = k;
  72. data[i] ^= localKey[(byte)(localKey[j] + k)];
  73. }
  74. }
  75. }
  76. }