2
0

DecryptionHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 long 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 long 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. else if (find_key_type == 3)
  133. {
  134. string searchString = "-----BEGIN PUBLIC KEY-----";
  135. }
  136. return null;
  137. }
  138. public static string GetMD5(string text)
  139. {
  140. MD5 md5 = MD5.Create();
  141. byte[] bs = Encoding.UTF8.GetBytes(text);
  142. byte[] hs = md5.ComputeHash(bs);
  143. StringBuilder sb = new StringBuilder();
  144. foreach(byte b in hs)
  145. {
  146. sb.Append(b.ToString("x2"));
  147. }
  148. return sb.ToString();
  149. }
  150. public static void DecryptDB(string file, string to_file, byte[] password_bytes)
  151. {
  152. //数据库头16字节是盐值
  153. byte[] salt_key = new byte[16];
  154. FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
  155. fileStream.Read(salt_key, 0, 16);
  156. //HMAC验证时用的盐值需要亦或0x3a
  157. byte[] hmac_salt = new byte[16];
  158. for (int i = 0; i < salt_key.Length; i++)
  159. {
  160. hmac_salt[i] = (byte)(salt_key[i] ^ 0x3a);
  161. }
  162. //计算保留段长度
  163. long reserved = IV_SIZE;
  164. reserved += HMAC_SHA1_SIZE;
  165. reserved = ((reserved % AES_BLOCK_SIZE) == 0) ? reserved : ((reserved / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE;
  166. //密钥扩展,分别对应AES解密密钥和HMAC验证密钥
  167. byte[] key = new byte[KEY_SIZE];
  168. byte[] hmac_key = new byte[KEY_SIZE];
  169. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(password_bytes, password_bytes.Length, salt_key, salt_key.Length, DEFAULT_ITER, key.Length, key);
  170. OpenSSLInterop.PKCS5_PBKDF2_HMAC_SHA1(key, key.Length, hmac_salt, hmac_salt.Length, 2, hmac_key.Length, hmac_key);
  171. long page_no = 0;
  172. long offset = 16;
  173. Console.WriteLine("开始解密...");
  174. var hmac_sha1 = HMAC.Create("HMACSHA1");
  175. hmac_sha1!.Key = hmac_key;
  176. List<byte> decrypted_file_bytes = new List<byte>();
  177. FileStream tofileStream = new FileStream(to_file, FileMode.OpenOrCreate, FileAccess.Write);
  178. using (fileStream)
  179. {
  180. try
  181. {
  182. // 当前分页小于计算分页数
  183. while (page_no < fileStream.Length / DEFAULT_PAGESIZE)
  184. {
  185. // 读内容
  186. byte[] decryped_page_bytes = new byte[DEFAULT_PAGESIZE];
  187. byte[] going_to_hashed = new byte[DEFAULT_PAGESIZE - reserved - offset + IV_SIZE + 4];
  188. fileStream.Seek((page_no * DEFAULT_PAGESIZE) + offset, SeekOrigin.Begin);
  189. fileStream.Read(going_to_hashed, 0, Convert.ToInt32(DEFAULT_PAGESIZE - reserved - offset + IV_SIZE));
  190. // 分页标志
  191. var page_bytes = BitConverter.GetBytes(page_no + 1);
  192. page_bytes.CopyTo(going_to_hashed, DEFAULT_PAGESIZE - reserved - offset + IV_SIZE);
  193. var hash_mac_compute = hmac_sha1.ComputeHash(going_to_hashed, 0, going_to_hashed.Length);
  194. // 取分页hash
  195. byte[] hash_mac_cached = new byte[hash_mac_compute.Length];
  196. fileStream.Seek((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved + IV_SIZE, SeekOrigin.Begin);
  197. fileStream.Read(hash_mac_cached, 0, hash_mac_compute.Length);
  198. if (!hash_mac_compute.SequenceEqual(hash_mac_cached) && page_no == 0)
  199. {
  200. Console.WriteLine("Hash错误...");
  201. return;
  202. }
  203. else
  204. {
  205. if (page_no == 0)
  206. {
  207. var header_bytes = Encoding.ASCII.GetBytes(SQLITE_HEADER);
  208. header_bytes.CopyTo(decryped_page_bytes, 0);
  209. }
  210. // 加密内容
  211. byte[] page_content = new byte[DEFAULT_PAGESIZE - reserved - offset];
  212. fileStream.Seek((page_no * DEFAULT_PAGESIZE) + offset, SeekOrigin.Begin);
  213. fileStream.Read(page_content, 0, Convert.ToInt32(DEFAULT_PAGESIZE - reserved - offset));
  214. // iv
  215. byte[] iv = new byte[16];
  216. fileStream.Seek((page_no * DEFAULT_PAGESIZE) + (DEFAULT_PAGESIZE - reserved), SeekOrigin.Begin);
  217. fileStream.Read(iv, 0, 16);
  218. var decrypted_content = AESDecrypt(page_content, key, iv);
  219. decrypted_content.CopyTo(decryped_page_bytes, offset);
  220. // 保留
  221. byte[] reserved_byte = new byte[reserved];
  222. fileStream.Seek((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved, SeekOrigin.Begin);
  223. fileStream.Read(reserved_byte, 0, Convert.ToInt32(reserved));
  224. reserved_byte.CopyTo(decryped_page_bytes, DEFAULT_PAGESIZE - reserved);
  225. tofileStream.Write(decryped_page_bytes, 0, decryped_page_bytes.Length);
  226. }
  227. page_no++;
  228. offset = 0;
  229. }
  230. }catch(Exception ex)
  231. {
  232. File.AppendAllText("err.log", "page=>" + page_no.ToString() + "\r\n");
  233. File.AppendAllText("err.log", "size=>" + fileStream.Length.ToString() + "\r\n");
  234. File.AppendAllText("err.log", "postion=>" + ((page_no * DEFAULT_PAGESIZE) + offset).ToString() + "\r\n");
  235. File.AppendAllText("err.log", ex.ToString() + "\r\n");
  236. }
  237. }
  238. /*
  239. * 旧版解密
  240. while (page_no < fileStream.Length / DEFAULT_PAGESIZE)
  241. {
  242. byte[] decryped_page_bytes = new byte[DEFAULT_PAGESIZE];
  243. byte[] going_to_hashed = new byte[DEFAULT_PAGESIZE - reserved - offset + IV_SIZE + 4];
  244. db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset + IV_SIZE).ToArray().CopyTo(going_to_hashed, 0);
  245. var page_bytes = BitConverter.GetBytes(page_no + 1);
  246. page_bytes.CopyTo(going_to_hashed, DEFAULT_PAGESIZE - reserved - offset + IV_SIZE);
  247. //计算分页的Hash
  248. var hash_mac_compute = hmac_sha1.ComputeHash(going_to_hashed, 0, going_to_hashed.Length);
  249. var hash_mac_cached = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved + IV_SIZE).Take(hash_mac_compute.Length).ToArray();
  250. //对比两个Hash
  251. if (!hash_mac_compute.SequenceEqual(hash_mac_cached))
  252. {
  253. Console.WriteLine("Hash错误...");
  254. return decrypted_file_bytes.ToArray();
  255. }
  256. else
  257. {
  258. Console.WriteLine($"解密第[{page_no + 1}]页");
  259. if (page_no == 0)
  260. {
  261. var header_bytes = Encoding.ASCII.GetBytes(SQLITE_HEADER);
  262. header_bytes.CopyTo(decryped_page_bytes, 0);
  263. }
  264. var encrypted_content = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + offset).Take(DEFAULT_PAGESIZE - reserved - offset).ToArray();
  265. var iv = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + (DEFAULT_PAGESIZE - reserved)).Take(16).ToArray();
  266. var decrypted_content = DecryptionHelper.AESDecrypt(encrypted_content, key, iv);
  267. decrypted_content.CopyTo(decryped_page_bytes, offset);
  268. var reserved_bytes = db_file_bytes.Skip((page_no * DEFAULT_PAGESIZE) + DEFAULT_PAGESIZE - reserved).Take(reserved).ToArray();
  269. reserved_bytes.CopyTo(decryped_page_bytes, DEFAULT_PAGESIZE - reserved);
  270. }
  271. page_no++;
  272. offset = 0;
  273. foreach (var item in decryped_page_bytes)
  274. {
  275. decrypted_file_bytes.Add(item);
  276. }
  277. }*/
  278. tofileStream.Close();
  279. tofileStream.Dispose();
  280. }
  281. public static byte[] AESDecrypt(byte[] content, byte[] key, byte[] iv)
  282. {
  283. Aes rijndaelCipher = Aes.Create();
  284. rijndaelCipher.Mode = CipherMode.CBC;
  285. rijndaelCipher.Padding = PaddingMode.None;
  286. rijndaelCipher.KeySize = 256;
  287. rijndaelCipher.BlockSize = 128;
  288. rijndaelCipher.Key = key;
  289. rijndaelCipher.IV = iv;
  290. ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
  291. byte[] plain_bytes = transform.TransformFinalBlock(content, 0, content.Length);
  292. return plain_bytes;
  293. }
  294. private static string BytesToHex(byte[] bytes)
  295. {
  296. return BitConverter.ToString(bytes, 0).Replace("-", string.Empty).ToLower().ToUpper();
  297. }
  298. private readonly static List<byte[]> ImgHeader = new List<byte[]>()
  299. {
  300. new byte[] { 0xFF, 0xD8 },//JPG
  301. new byte[] { 0x89, 0x50 },//PNG
  302. new byte[] { 0x42, 0x4D },//BMP
  303. new byte[] { 0x47, 0x49 },//GIF
  304. new byte[] { 0x49, 0x49 },//TIF
  305. new byte[] { 0x4D, 0x4D },//TIF
  306. };
  307. public static byte[] DecImage(string source)
  308. {
  309. //读取数据
  310. byte[] fileBytes = File.ReadAllBytes(source);
  311. //算差异转换
  312. foreach (byte[] b in ImgHeader)
  313. {
  314. byte t = (byte)(fileBytes[0] ^ b[0]);
  315. byte[] decData = fileBytes.Select(b => (byte)(b ^ t)).ToArray();
  316. if (b[1] != decData[1])
  317. continue;
  318. else
  319. {
  320. return decData;
  321. }
  322. }
  323. return new byte[0];
  324. }
  325. public static string CheckFileType(byte[] data)
  326. {
  327. if (data[0] == 0xFF && data[1] == 0xD8)
  328. return ".jpg";
  329. else if (data[0] == 0x89 && data[1] == 0x50)
  330. return ".png";
  331. else if (data[0] == 0x42 && data[1] == 0X4D)
  332. return ".bmp";
  333. else if (data[0] == 0x47 && data[1] == 0x49)
  334. return ".gif";
  335. else if (data[0] == 0x49 && data[1] == 0x49)
  336. return ".tif";
  337. else if (data[0] == 0x4D && data[1] == 0x4D)
  338. return ".tif";
  339. else
  340. return ".dat";
  341. }
  342. public static string SaveDecImage(byte[] fileRaw,string source,string to_dir,string type)
  343. {
  344. FileInfo fileInfo = new FileInfo(source);
  345. string fileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - 4);
  346. string saveFilePath = Path.Combine(to_dir, fileName + type);
  347. using (FileStream fileStream = File.OpenWrite(saveFilePath))
  348. {
  349. fileStream.Write(fileRaw, 0, fileRaw.Length);
  350. fileStream.Flush();
  351. }
  352. return saveFilePath;
  353. }
  354. public static void DecryUserData(byte[] key, string source, string to,CreateWorkViewModel viewModel)
  355. {
  356. string dbPath = source;
  357. string decPath = to;
  358. if (!Directory.Exists(decPath))
  359. Directory.CreateDirectory(decPath);
  360. string[] filePath = Directory.GetFiles(dbPath);
  361. foreach (string file in filePath)
  362. {
  363. FileInfo info = new FileInfo(file);
  364. viewModel.LabelStatus = "正在解密" + info.Name;
  365. string to_file = Path.Combine(decPath, info.Name);
  366. DecryptDB(file,to_file, key);
  367. }
  368. }
  369. }
  370. }