DecryptionHelper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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, int find_key_type, 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 (find_key_type == 1)
  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 if(find_key_type == 2)
  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 (NativeAPI.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 (NativeAPI.ReadProcessMemory(process.Handle, (IntPtr)addr, key_bytes, key_bytes.Length, out _))
  79. {
  80. return key_bytes;
  81. }
  82. }
  83. }
  84. }
  85. else if (find_key_type == 3)
  86. {
  87. string searchString = "-----BEGIN PUBLIC KEY-----";
  88. List<long> addr = NativeAPIHelper.SearchProcessAllMemory(process, searchString);
  89. if (addr.Count > 0)
  90. {
  91. foreach (long a in addr)
  92. {
  93. byte[] buffer = new byte[module.ModuleMemorySize];
  94. byte[] search = BitConverter.GetBytes(a);
  95. Array.Resize(ref search, 8);
  96. int read = 0;
  97. List<int> offset = new List<int>();
  98. if (NativeAPI.ReadProcessMemory(process.Handle, module.BaseAddress, buffer, buffer.Length, out read))
  99. {
  100. for (int i = 0; i < buffer.Length - 1; i++)
  101. {
  102. if (buffer[i] == search[0])
  103. {
  104. for (int s = 1; s < search.Length; s++)
  105. {
  106. if (buffer[i + s] != search[s])
  107. break;
  108. if (s == search.Length - 1)
  109. {
  110. long iii = (long)module.BaseAddress + i - 0xd8;
  111. byte[] key = new byte[8];
  112. if (NativeAPI.ReadProcessMemory(process.Handle, new IntPtr(iii), key, key.Length, out _))
  113. {
  114. ulong key_addr = BitConverter.ToUInt64(key, 0);
  115. byte[] key_bytes = new byte[32];
  116. NativeAPI.ReadProcessMemory(process.Handle, (IntPtr)key_addr, key_bytes, key_bytes.Length, out _);
  117. string key1 = BitConverter.ToString(key_bytes, 0);
  118. return key_bytes;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. }
  127. else
  128. {
  129. throw new Exception("搜索不到微信账号,请确认用户名是否正确,如错误请重新新建工作区,务必确认账号是否正确");
  130. }
  131. }
  132. return null;
  133. }
  134. public static byte[] DecryptDB(byte[] db_file_bytes, byte[] password_bytes)
  135. {
  136. //数据库头16字节是盐值
  137. var salt = db_file_bytes.Take(16).ToArray();
  138. //HMAC验证时用的盐值需要亦或0x3a
  139. byte[] hmac_salt = new byte[16];
  140. for (int i = 0; i < salt.Length; i++)
  141. {
  142. hmac_salt[i] = (byte)(salt[i] ^ 0x3a);
  143. }
  144. //计算保留段长度
  145. int reserved = IV_SIZE;
  146. reserved += HMAC_SHA1_SIZE;
  147. reserved = ((reserved % AES_BLOCK_SIZE) == 0) ? reserved : ((reserved / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;
  148. //密钥扩展,分别对应AES解密密钥和HMAC验证密钥
  149. byte[] key = new byte[KEY_SIZE];
  150. byte[] hmac_key = new byte[KEY_SIZE];
  151. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(password_bytes, password_bytes.Length, salt, salt.Length, DEFAULT_ITER, key.Length, key);
  152. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(key, key.Length, hmac_salt, hmac_salt.Length, 2, hmac_key.Length, hmac_key);
  153. int page_no = 0;
  154. int offset = 16;
  155. Console.WriteLine("开始解密...");
  156. var hmac_sha1 = HMAC.Create("HMACSHA1");
  157. hmac_sha1!.Key = hmac_key;
  158. List<byte> decrypted_file_bytes = new List<byte>();
  159. while (page_no < db_file_bytes.Length / DEFAULT_PAGESIZE)
  160. {
  161. byte[] decryped_page_bytes = new byte[DEFAULT_PAGESIZE];
  162. byte[] going_to_hashed = new byte[DEFAULT_PAGESIZE - reserved - offset + IV_SIZE + 4];
  163. db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset + IV_SIZE).ToArray().CopyTo(going_to_hashed, 0);
  164. var page_bytes = BitConverter.GetBytes(page_no + 1);
  165. page_bytes.CopyTo(going_to_hashed, DEFAULT_PAGESIZE - reserved - offset + IV_SIZE);
  166. //计算分页的Hash
  167. var hash_mac_compute = hmac_sha1.ComputeHash(going_to_hashed, 0, going_to_hashed.Length);
  168. //取出分页中存储的Hash
  169. var hash_mac_cached = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved + IV_SIZE).Take(hash_mac_compute.Length).ToArray();
  170. //对比两个Hash
  171. if (!hash_mac_compute.SequenceEqual(hash_mac_cached))
  172. {
  173. Console.WriteLine("Hash错误...");
  174. return decrypted_file_bytes.ToArray();
  175. }
  176. else
  177. {
  178. Console.WriteLine($"解密第[{page_no + 1}]页");
  179. if (page_no == 0)
  180. {
  181. var header_bytes = Encoding.ASCII.GetBytes(SQLITE_HEADER);
  182. header_bytes.CopyTo(decryped_page_bytes, 0);
  183. }
  184. var encrypted_content = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset).ToArray();
  185. var iv = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + (DEFAULT_PAGESIZE - reserved)).Take(16).ToArray();
  186. var decrypted_content = DecryptionHelper.AESDecrypt(encrypted_content, key, iv);
  187. decrypted_content.CopyTo(decryped_page_bytes, offset);
  188. var reserved_bytes = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved).Take(reserved).ToArray();
  189. reserved_bytes.CopyTo(decryped_page_bytes, DEFAULT_PAGESIZE - reserved);
  190. }
  191. page_no++;
  192. offset = 0;
  193. foreach (var item in decryped_page_bytes)
  194. {
  195. decrypted_file_bytes.Add(item);
  196. }
  197. }
  198. return decrypted_file_bytes.ToArray();
  199. }
  200. public static byte[] AESDecrypt(byte[] content, byte[] key, byte[] iv)
  201. {
  202. Aes rijndaelCipher = Aes.Create();
  203. rijndaelCipher.Mode = CipherMode.CBC;
  204. rijndaelCipher.Padding = PaddingMode.None;
  205. rijndaelCipher.KeySize = 256;
  206. rijndaelCipher.BlockSize = 128;
  207. rijndaelCipher.Key = key;
  208. rijndaelCipher.IV = iv;
  209. ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  210. byte[] plain_bytes = transform.TransformFinalBlock(content, 0, content.Length);
  211. return plain_bytes;
  212. }
  213. private static string BytesToHex(byte[] bytes)
  214. {
  215. return BitConverter.ToString(bytes, 0).Replace("-", string.Empty).ToLower().ToUpper();
  216. }
  217. private readonly static List<byte[]> ImgHeader = new List<byte[]>()
  218. {
  219. new byte[] { 0xFF, 0xD8 },//JPG
  220. new byte[] { 0x89, 0x50 },//PNG
  221. new byte[] { 0x42, 0x4D },//BMP
  222. new byte[] { 0x47, 0x49 },//GIF
  223. new byte[] { 0x49, 0x49 },//TIF
  224. new byte[] { 0x4D, 0x4D },//TIF
  225. };
  226. public static byte[] DecImage(string source)
  227. {
  228. //读取数据
  229. byte[] fileBytes = File.ReadAllBytes(source);
  230. //算差异转换
  231. foreach (byte[] b in ImgHeader)
  232. {
  233. byte t = (byte)(fileBytes[0] ^ b[0]);
  234. byte[] decData = fileBytes.Select(b => (byte)(b ^ t)).ToArray();
  235. if (b[1] != decData[1])
  236. continue;
  237. else
  238. {
  239. return decData;
  240. }
  241. }
  242. return new byte[0];
  243. }
  244. public static string CheckFileType(byte[] data)
  245. {
  246. if (data[0] == 0xFF && data[1] == 0xD8)
  247. return ".jpg";
  248. else if (data[0] == 0x89 && data[1] == 0x50)
  249. return ".png";
  250. else if (data[0] == 0x42 && data[1] == 0X4D)
  251. return ".bmp";
  252. else if (data[0] == 0x47 && data[1] == 0x49)
  253. return ".gif";
  254. else if (data[0] == 0x49 && data[1] == 0x49)
  255. return ".tif";
  256. else if (data[0] == 0x4D && data[1] == 0x4D)
  257. return ".tif";
  258. else
  259. return ".dat";
  260. }
  261. public static string SaveDecImage(byte[] fileRaw,string source,string to_dir,string type)
  262. {
  263. FileInfo fileInfo = new FileInfo(source);
  264. string fileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
  265. string saveFilePath = Path.Combine(to_dir, fileName + type);
  266. using (FileStream fileStream = File.OpenWrite(saveFilePath))
  267. {
  268. fileStream.Write(fileRaw, 0, fileRaw.Length);
  269. fileStream.Flush();
  270. }
  271. return saveFilePath;
  272. }
  273. public static void DecryUserData(byte[] key, string source, string to,CreateWorkViewModel viewModel)
  274. {
  275. string dbPath = source;
  276. string decPath = to;
  277. if (!Directory.Exists(decPath))
  278. Directory.CreateDirectory(decPath);
  279. string[] filePath = Directory.GetFiles(dbPath);
  280. foreach (string file in filePath)
  281. {
  282. FileInfo info = new FileInfo(file);
  283. viewModel.LabelStatus = "正在解密" + info.Name;
  284. var db_bytes = File.ReadAllBytes(file);
  285. var decrypted_file_bytes = DecryptDB(db_bytes, key);
  286. if (decrypted_file_bytes == null || decrypted_file_bytes.Length == 0)
  287. {
  288. Console.WriteLine("解密后的数组为空");
  289. }
  290. else
  291. {
  292. File.WriteAllBytes(Path.Combine(decPath, info.Name), decrypted_file_bytes);
  293. }
  294. }
  295. }
  296. }
  297. }