DecryptionHelper.cs 11 KB

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