DecryptionHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Text.Json.Serialization;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. using WechatBakTool.Model;
  14. using WechatBakTool.Pages;
  15. using WechatBakTool.ViewModel;
  16. namespace WechatBakTool.Helpers
  17. {
  18. public class DecryptionHelper
  19. {
  20. const int IV_SIZE = 16;
  21. const int HMAC_SHA1_SIZE = 20;
  22. const int KEY_SIZE = 32;
  23. const int AES_BLOCK_SIZE = 16;
  24. const int DEFAULT_ITER = 64000;
  25. const int DEFAULT_PAGESIZE = 4096; //4048数据 + 16IV + 20 HMAC + 12
  26. const string SQLITE_HEADER = "SQLite format 3";
  27. public static byte[]? GetWechatKey(string pid, bool mem_find_key, string account)
  28. {
  29. Process process = Process.GetProcessById(int.Parse(pid));
  30. ProcessModule? module = ProcessHelper.FindProcessModule(process.Id, "WeChatWin.dll");
  31. if (module == null)
  32. {
  33. return null;
  34. }
  35. string? version = module.FileVersionInfo.FileVersion;
  36. if (version == null)
  37. {
  38. return null;
  39. }
  40. if (!mem_find_key)
  41. {
  42. List<VersionInfo>? info = null;
  43. string json = File.ReadAllText("version.json");
  44. info = JsonConvert.DeserializeObject<List<VersionInfo>?>(json);
  45. if (info == null)
  46. return null;
  47. if (info.Count == 0)
  48. return null;
  49. VersionInfo? cur = info.Find(x => x.Version == version);
  50. if (cur == null)
  51. return null;
  52. //这里加的是版本偏移量,兼容不同版本把这个加给改了
  53. long baseAddress = (long)module.BaseAddress + cur.BaseAddr;
  54. byte[]? bytes = ProcessHelper.ReadMemoryDate(process.Handle, (IntPtr)baseAddress, 8);
  55. if (bytes != null)
  56. {
  57. IntPtr baseAddress2 = (IntPtr)(((long)bytes[7] << 56) + ((long)bytes[6] << 48) + ((long)bytes[5] << 40) + ((long)bytes[4] << 32) + ((long)bytes[3] << 24) + ((long)bytes[2] << 16) + ((long)bytes[1] << 8) + (long)bytes[0]);
  58. byte[]? twoGet = ProcessHelper.ReadMemoryDate(process.Handle, baseAddress2, 32);
  59. if (twoGet != null)
  60. {
  61. string key = BytesToHex(twoGet);
  62. return twoGet;
  63. }
  64. }
  65. }
  66. else
  67. {
  68. List<int> read = ProcessHelper.FindProcessMemory(process.Handle, module, account);
  69. if (read.Count >= 2)
  70. {
  71. byte[] buffer = new byte[8];
  72. int key_offset = read[1] - 64;
  73. if (ProcessHelper.ReadProcessMemory(process.Handle, module.BaseAddress + key_offset, buffer, buffer.Length, out _))
  74. {
  75. ulong addr = BitConverter.ToUInt64(buffer, 0);
  76. byte[] key_bytes = new byte[32];
  77. if (ProcessHelper.ReadProcessMemory(process.Handle, (IntPtr)addr, key_bytes, key_bytes.Length, out _))
  78. {
  79. return key_bytes;
  80. }
  81. }
  82. }
  83. else
  84. {
  85. throw new Exception("搜索不到微信账号,请确认用户名是否正确,如错误请重新新建工作区,务必确认账号是否正确");
  86. }
  87. }
  88. return null;
  89. }
  90. public static byte[] DecryptDB(byte[] db_file_bytes, byte[] password_bytes)
  91. {
  92. //数据库头16字节是盐值
  93. var salt = db_file_bytes.Take(16).ToArray();
  94. //HMAC验证时用的盐值需要亦或0x3a
  95. byte[] hmac_salt = new byte[16];
  96. for (int i = 0; i < salt.Length; i++)
  97. {
  98. hmac_salt[i] = (byte)(salt[i] ^ 0x3a);
  99. }
  100. //计算保留段长度
  101. int reserved = IV_SIZE;
  102. reserved += HMAC_SHA1_SIZE;
  103. reserved = ((reserved % AES_BLOCK_SIZE) == 0) ? reserved : ((reserved / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;
  104. //密钥扩展,分别对应AES解密密钥和HMAC验证密钥
  105. byte[] key = new byte[KEY_SIZE];
  106. byte[] hmac_key = new byte[KEY_SIZE];
  107. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(password_bytes, password_bytes.Length, salt, salt.Length, DEFAULT_ITER, key.Length, key);
  108. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(key, key.Length, hmac_salt, hmac_salt.Length, 2, hmac_key.Length, hmac_key);
  109. int page_no = 0;
  110. int offset = 16;
  111. Console.WriteLine("开始解密...");
  112. var hmac_sha1 = HMAC.Create("HMACSHA1");
  113. hmac_sha1!.Key = hmac_key;
  114. List<byte> decrypted_file_bytes = new List<byte>();
  115. while (page_no < db_file_bytes.Length / DEFAULT_PAGESIZE)
  116. {
  117. byte[] decryped_page_bytes = new byte[DEFAULT_PAGESIZE];
  118. byte[] going_to_hashed = new byte[DEFAULT_PAGESIZE - reserved - offset + IV_SIZE + 4];
  119. db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset + IV_SIZE).ToArray().CopyTo(going_to_hashed, 0);
  120. var page_bytes = BitConverter.GetBytes(page_no + 1);
  121. page_bytes.CopyTo(going_to_hashed, DEFAULT_PAGESIZE - reserved - offset + IV_SIZE);
  122. //计算分页的Hash
  123. var hash_mac_compute = hmac_sha1.ComputeHash(going_to_hashed, 0, going_to_hashed.Count());
  124. //取出分页中存储的Hash
  125. var hash_mac_cached = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved + IV_SIZE).Take(hash_mac_compute.Length).ToArray();
  126. //对比两个Hash
  127. if (!hash_mac_compute.SequenceEqual(hash_mac_cached))
  128. {
  129. Console.WriteLine("Hash错误...");
  130. return decrypted_file_bytes.ToArray();
  131. }
  132. else
  133. {
  134. Console.WriteLine($"解密第[{page_no + 1}]页");
  135. if (page_no == 0)
  136. {
  137. var header_bytes = Encoding.ASCII.GetBytes(SQLITE_HEADER);
  138. header_bytes.CopyTo(decryped_page_bytes, 0);
  139. }
  140. var encrypted_content = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset).ToArray();
  141. var iv = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + (DEFAULT_PAGESIZE - reserved)).Take(16).ToArray();
  142. var decrypted_content = DecryptionHelper.AESDecrypt(encrypted_content, key, iv);
  143. decrypted_content.CopyTo(decryped_page_bytes, offset);
  144. var reserved_bytes = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved).Take(reserved).ToArray();
  145. reserved_bytes.CopyTo(decryped_page_bytes, DEFAULT_PAGESIZE - reserved);
  146. }
  147. page_no++;
  148. offset = 0;
  149. foreach (var item in decryped_page_bytes)
  150. {
  151. decrypted_file_bytes.Add(item);
  152. }
  153. }
  154. return decrypted_file_bytes.ToArray();
  155. }
  156. public static byte[] AESDecrypt(byte[] content, byte[] key, byte[] iv)
  157. {
  158. Aes rijndaelCipher = Aes.Create();
  159. rijndaelCipher.Mode = CipherMode.CBC;
  160. rijndaelCipher.Padding = PaddingMode.None;
  161. rijndaelCipher.KeySize = 256;
  162. rijndaelCipher.BlockSize = 128;
  163. rijndaelCipher.Key = key;
  164. rijndaelCipher.IV = iv;
  165. ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  166. byte[] plain_bytes = transform.TransformFinalBlock(content, 0, content.Length);
  167. return plain_bytes;
  168. }
  169. private static string BytesToHex(byte[] bytes)
  170. {
  171. return BitConverter.ToString(bytes, 0).Replace("-", string.Empty).ToLower().ToUpper();
  172. }
  173. public static byte[] DecImage(string source)
  174. {
  175. //读取数据
  176. byte[] fileBytes = File.ReadAllBytes(source);
  177. //算差异转换
  178. byte key = GetImgKey(fileBytes);
  179. fileBytes = ConvertData(fileBytes, key);
  180. return fileBytes;
  181. }
  182. public static string CheckFileType(byte[] data)
  183. {
  184. switch (data[0])
  185. {
  186. case 0XFF: //byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF };
  187. {
  188. if (data[1] == 0xD8 && data[2] == 0xFF)
  189. {
  190. return ".jpg";
  191. }
  192. break;
  193. }
  194. case 0x89: //byte[] png = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
  195. {
  196. if (data[1] == 0x50 && data[2] == 0x4E && data[7] == 0x0A)
  197. {
  198. return ".png";
  199. }
  200. break;
  201. }
  202. case 0x42: //byte[] bmp = new byte[] { 0x42, 0x4D };
  203. {
  204. if (data[1] == 0X4D)
  205. {
  206. return ".bmp";
  207. }
  208. break;
  209. }
  210. case 0x47: //byte[] gif = new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39(0x37), 0x61 };
  211. {
  212. if (data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x38 && data[5] == 0x61)
  213. {
  214. return ".gif";
  215. }
  216. break;
  217. }
  218. case 0x49: // byte[] tif = new byte[] { 0x49, 0x49, 0x2A, 0x00 };
  219. {
  220. if (data[1] == 0x49 && data[2] == 0x2A && data[3] == 0x00)
  221. {
  222. return ".tif";
  223. }
  224. break;
  225. }
  226. case 0x4D: //byte[] tif = new byte[] { 0x4D, 0x4D, 0x2A, 0x00 };
  227. {
  228. if (data[1] == 0x4D && data[2] == 0x2A && data[3] == 0x00)
  229. {
  230. return ".tif";
  231. }
  232. break;
  233. }
  234. }
  235. return ".dat";
  236. }
  237. private static byte GetImgKey(byte[] fileRaw)
  238. {
  239. byte[] raw = new byte[8];
  240. for (int i = 0; i < 8; i++)
  241. {
  242. raw[i] = fileRaw[i];
  243. }
  244. for (byte key = 0x01; key < 0xFF; key++)
  245. {
  246. byte[] buf = new byte[8];
  247. raw.CopyTo(buf, 0);
  248. if (CheckFileType(ConvertData(buf, key)) != ".dat")
  249. {
  250. return key;
  251. }
  252. }
  253. return 0x00;
  254. }
  255. private static byte[] ConvertData(byte[] data, byte key)
  256. {
  257. for (int i = 0; i < data.Length; i++)
  258. {
  259. data[i] ^= key;
  260. }
  261. return data;
  262. }
  263. public static string SaveDecImage(byte[] fileRaw,string source,string to_dir,string type)
  264. {
  265. FileInfo fileInfo = new FileInfo(source);
  266. string fileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
  267. string saveFilePath = Path.Combine(to_dir, fileName + type);
  268. using (FileStream fileStream = File.OpenWrite(saveFilePath))
  269. {
  270. fileStream.Write(fileRaw, 0, fileRaw.Length);
  271. fileStream.Flush();
  272. }
  273. return saveFilePath;
  274. }
  275. public static void DecryUserData(byte[] key, string source, string to,CreateWorkViewModel viewModel)
  276. {
  277. string dbPath = source;
  278. string decPath = to;
  279. if (!Directory.Exists(decPath))
  280. Directory.CreateDirectory(decPath);
  281. string[] filePath = Directory.GetFiles(dbPath);
  282. foreach (string file in filePath)
  283. {
  284. FileInfo info = new FileInfo(file);
  285. viewModel.LabelStatus = "正在解密" + info.Name;
  286. var db_bytes = File.ReadAllBytes(file);
  287. var decrypted_file_bytes = DecryptDB(db_bytes, key);
  288. if (decrypted_file_bytes == null || decrypted_file_bytes.Length == 0)
  289. {
  290. Console.WriteLine("解密后的数组为空");
  291. }
  292. else
  293. {
  294. File.WriteAllBytes(Path.Combine(decPath, info.Name), decrypted_file_bytes);
  295. }
  296. }
  297. }
  298. }
  299. }