本文前部分发表于 冷月的博客, 基于 CC BY-NC-SA 4.0 共享.
0. 引言
为了让每个人都可以把自己练入 LLM, 制作自己的数字分身. 解析 QQ 数据库无疑是快速获得语料库的最佳途径. 然而, 众所周知, QQ 的数据库是加密的 SQLite 数据库, 且不幸的是, 在最新的 NTQQ 中数据库的加密方式已经发生了变化. 本文将介绍如何解析 Mac 的 NTQQ 数据库.
参考资料 (win): QQBackup/qq-win-db-key
该方案于 2023 年 9 月 19 日在 NTQQ 6.9.17 上测试通过. 严禁用于非法用途.
1. 准备工作
在开始解析之前, 我们需要准备一些工具:
- NTQQ
- DB Browser for SQLite
- LLDB (MacOS 自带, 注意需要关闭 SIP)
- Hopper Disassembler
因为我们的流程非常简单, 免费版的 Hopper 即可满足需求.
2. 分析
你需要先准备一个自己喜欢的工作目录, 并且将 NTQQ 的 Library 复制到当前目录下:
cp /Applications/QQ.app/Contents/Resources/app/wrapper.node .
随后, 你需要使用 Hopper 打开 wrapper.node 在 Mac M1/M2 上需要选择 aarch64, 并且搜索 nt_sqlite3_key_v2.



如上图所示, 我们可以跳转到引用该函数的地方, 随后记下该函数地址:00000000029340ac
3. 断点 & 调试
随后我们运行 NTQQ, 找到它的进程 ID, 并且使用 LLDB 进行调试:
❯ ps aux | grep /Applications/QQ.app/Contents/MacOS/QQ
user 78488 1.5 0.5 1584651520 162000 ?? S 1:59PM 0:00.61 /Applications/QQ.app/Contents/MacOS/QQ
lldb -p 78488
我们需要寻找 wrapper.node 的加载地址:
(lldb) image list -o -f | grep /Applications/QQ.app/Contents/Resources/app/wrapper.node
[ 0] 0x0000000110088000 /Applications/QQ.app/Contents/Resources/app/wrapper.node
接下来进行一个简单的数学运算, 计算出 nt_sqlite3_key_v2 的地址:
(lldb) expr 0x0000000110088000 + 0x00000000029340ac
(unsigned long) $0 = 4590354168
设置断点并且继续运行:
(lldb) br s -a 4590354168
Breakpoint 1: where = wrapper.node`___lldb_unnamed_symbol287604, address = 0x00000001119b3ef8
(lldb) c
Process 78488 resuming
点击登录后, 如无意外, 你会看到断点被命中, 并且进入了 nt_sqlite3_key_v2 函数, 如下图所示:
参考函数签名:
int sqlite3_key_v2(
sqlite3 *db, /* Database to be keyed, x0 */
const char *zDbName, /* Name of the database, x1 */
const void *pKey, int nKey /* The key, x2, x3 */
);
接下来解析 16 个字符即可:
(lldb) register read x2
x2 = 0x000001140838bdc0
(lldb) memory read --format c --count 16 --size 1 0x000001140838bdc0
0x12801b34010: 5WbDc@ITR(%Atz`^
至此, 我们已经成功解析出了 NTQQ 的数据库密钥:5WbDc@ITR(%Atz`^
4. 解密
数据库位于 (注意 MD5 可能会随着 QQ 的版本更新而改变):
/Users/user/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/nt_qq_{MD5}/nt_db
复制你需要的文件, 如 nt_msg.db:
cp "/Users/user/Library/Containers/com.tencent.qq/Data/Library/Application Support/QQ/nt_qq_cc067b8bcbf8980fabd93574e09d9efa/nt_db/nt_msg.db" nt_msg_1.clean.db
移除无关文件头 使用tail命令:
tail -c +1025 nt_msg.db > nt_msg_1.clean.db
完成后,得到nt_msg_1.clean.db文件。
5.打开数据库
使用DB Browser for SQLite工具打开数据库。
在这个界面分别输入上面的密码,以及选择Custom,更改KDF iterations为4000,HMAC algorithm为SHA1,点击OK。

进入数据库之后点击Tools,选择Set Encryptions.然后点击OK就行 下次就没有密码了。

6.使用python脚本导出数据。
下面写了一个脚本用来导出私聊记录,分别同时导出所有的私聊记录,以及根据时间的所有聊天记录。如下图:
并且用昵称命名。


json格式

txt格式

以及CSV和XML。
import json
import os
import sqlite3
import time
import blackboxprotobuf
ME = 0 # 你的QQ号
ME_NAME = "" # 你的QQ昵称
LIMIT_LEN = 0 # 限制导出的人数
def get_content_s(content):
s = ""
for c in content:
if c["45002"] == 1:
# 文本消息
s += str(c["45101"])
elif c["45002"] == 2:
# 图片消息
s += f"[img:file={c['45402']},url=https://c2cpicdw.qpic.cn/{c['45802']}]"
elif c["45002"] == 3:
# 文件消息
s += f"[file:{c['45402']}]"
elif c["45002"] == 4:
pass
elif c["45002"] == 5:
# 视频消息
s += f"[video:file={c['45402']},url=......]"
elif c["45002"] == 6:
# 表情消息
if c["45003"] == 1:
s += f"[普通表情:{c['47601']}]"
elif c["45003"] == 2:
s += f"[大表情:{c['47602']}]"
elif c["45003"] == 3:
s += f"[大表情:{c['47602']}]"
elif c["45002"] == 7:
# 回复消息
s += f"[回复:{c["47423"]["45101"]}]"
elif c["45002"] == 8:
# 接收文件消息
s += f"[file:{str(c['45002'])}]"
elif c["45002"] == 9:
pass
elif c["45002"] == 10:
# 邮件消息
s += f"[mail:{c['47901']}]"
else:
s += f"[未知消息类型:{c['45002']}]"
return s
def get_content(content):
if type(content) is dict:
return get_content_s([content])
elif type(content) is list:
return get_content_s(content)
class Person:
def __init__(self, col):
self.id = col[0]
self.name = col[1]
self.remark = col[2] if col[2] != "" else col[1]
class Chat:
def __init__(self, me, you, persons: [Person]):
self.me = get_name(me, persons)
self.you = get_name(you, persons)
self.p = {me, you}
self.msgs = []
def store_json(self, export_path: str):
if not os.path.exists(export_path + "JSON"):
os.makedirs(export_path + "JSON")
with open(export_path + "JSON/" + f"{self.you}{self.me}{self.p}chat.json".replace('/', ''), "w",
encoding="utf-8") as f:
json.dump({"count": len(self.msgs), "data": [msg.__dict__ for msg in self.msgs]}, f, ensure_ascii=False,
indent=4)
class Msg:
def __init__(self, col):
self.id = col[2]
self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(col[1]))
self.sender_id = col[3]
self.sender_name = ""
self.recipient_id = ME if col[4] == col[3] else col[4]
self.recipient_name = ""
self.content = get_content(blackboxprotobuf.decode_message(col[0])[0]['40800'])
def get_name(id, persons: [Person]):
for person in persons:
if id == ME:
return ""
if person.id == id:
return person.remark if person.remark != "" else person.name
def get_msg(cur) -> list[Msg]:
cur.execute(f"""SELECT "40800","40050","40001","40033","40030","40040" FROM c2c_msg_table order by "40050";""")
M = []
for col in cur:
try:
msg = Msg(col)
M.append(msg)
# print(msg.time, msg.sender_id, "---->", msg.recipient_id, ": ", msg.content)
except:
# print("Error", col)
pass
return M
def get_person(db_path: str) -> list[Person]:
conn = sqlite3.connect(db_path)
cur = conn.cursor()
cur.execute(f"""SELECT "1002","20002","20009" FROM profile_info_v2 ORDER by "20009" DESC limit {LIMIT_LEN};""")
P = []
for col in cur:
person = Person(col)
P.append(person)
# print(person.qun_id, person.id, person.name, person.remark, person.qun_remark, person.qun_remark_id)
cur.close()
return P
def set_remark(persons: [Person], msgs: [Msg]):
for msg in msgs:
for person in persons:
if msg.sender_id == person.id:
msg.sender_name = person.remark
elif msg.recipient_id == person.id:
msg.recipient_name = person.remark
if msg.sender_id == ME:
msg.sender_name = ME_NAME
elif msg.recipient_id == ME:
msg.recipient_name = ME_NAME
return msgs
def store_all(export_path: str, msgs: [Msg], ft: list[str]):
if "json" in ft:
store_json(export_path, msgs)
if "csv" in ft:
store_csv(export_path, msgs)
if "xml" in ft:
store_xml(export_path, msgs)
if "txt" in ft:
store_txt(export_path, msgs)
def store_json(export_path: str, msgs: [Msg]):
with open(export_path + "total_chat.json", "w", encoding="utf-8") as f:
json.dump([msg.__dict__ for msg in msgs], f, ensure_ascii=False, indent=4)
def store_csv(export_path: str, msgs: [Msg]):
with open(export_path + "total_chat.csv", "w", encoding="utf-8") as f:
f.write("time,sender_name,sender_id,recipient_name,recipient_id,content\n")
for msg in msgs:
f.write(
f"{msg.time},{msg.sender_name},{msg.sender_id},{msg.recipient_name},{msg.recipient_id},{msg.content.replace("\n", " ")}\n")
f.close()
def store_xml(export_path: str, msgs: [Msg]):
with open(export_path + "total_chat.xml", "w", encoding="utf-8") as f:
f.write("<chat>\n")
for msg in msgs:
f.write(
f" <msg time='{msg.time}' sender='{msg.sender_name}' recipient='{msg.recipient_name}'>{msg.content.replace("\n", " ")}</msg>\n")
f.write("</chat>")
f.close()
def store_txt(export_path: str, msgs: [Msg]):
with open(export_path + "total_chat.txt", "w", encoding="utf-8") as f:
for msg in msgs:
f.write(f"{msg.time} {msg.sender_name}-->{msg.recipient_name}: {msg.content.replace("\n", " ")}\n")
f.close()
def store_p(export_path: str, msgs: [Msg], persons: [Person], ft: list[str]):
store_all(export_path, msgs, ft)
chats = []
chat_ps = []
for msg in msgs:
if msg.sender_id == 0 or msg.recipient_id == 0:
continue
if {msg.sender_id, msg.recipient_id} not in chat_ps:
chat_ps.append({msg.sender_id, msg.recipient_id}, )
chat = Chat(msg.sender_id, msg.recipient_id, persons)
chat.msgs.append(msg)
chats.append(chat)
else:
for chat in chats:
if {msg.sender_id, msg.recipient_id} == chat.p:
chat.msgs.append(msg)
print("共有", len(chats), "个聊天")
all_msg = []
for chat in chats:
if "json" in ft:
chat.store_json(export_path)
if "txt" in ft:
if not os.path.exists(export_path + "TXT/"):
os.makedirs(export_path + "TXT")
with open(export_path + "TXT/" + f"{chat.you}{chat.me}{chat.p}.txt".replace('/', ''), "w",
encoding="utf-8") as f:
for msg in chat.msgs:
f.write(f"{msg.time} {msg.sender_name}-->{msg.recipient_name}: {msg.content.replace("\n", " ")}\n")
if "xml" in ft:
if not os.path.exists(export_path + "XML/"):
os.makedirs(export_path + "XML")
with open(export_path + "XML/" + f"{chat.you}{chat.me}{chat.p}.xml".replace('/', ''), "w",
encoding="utf-8") as f:
f.write(f"<chat me='{chat.me}' you='{chat.you}' p='{chat.p}'>\n")
for msg in chat.msgs:
f.write(
f" <msg time='{msg.time}' sender='{msg.sender_name}' recipient='{msg.recipient_name}'>{msg.content.replace("\n", " ")}</msg>\n")
f.write("</chat>")
if "csv" in ft:
if not os.path.exists(export_path + "CSV"):
os.makedirs(export_path + "CSV")
# print(export_path + f"CSV/{chat.you}{chat.me}{chat.p}.csv".replace('/', ''))
with open(export_path + "CSV/" + f"{chat.you}{chat.me}{chat.p}.csv".replace('/', ''), "w",
encoding="utf-8") as f:
f.write("time,sender_name,sender_id,recipient_name,recipient_id,content\n")
for msg in chat.msgs:
f.write(
f"{msg.time},{msg.sender_name},{msg.sender_id},{msg.recipient_name},{msg.recipient_id},{msg.content.replace("\n", " ")}\n")
f.close()
if "ddd" in ft:
for msg in chat.msgs:
all_msg.append(msg)
print(chat.me, chat.you, chat.p)
print("共有", len(chat.msgs), "条消息")
if "ddd" in ft:
with open("train/total_chat_rank.json", "w", encoding="utf-8") as f:
json.dump([msg.__dict__ for msg in all_msg], f, ensure_ascii=False, indent=4)
def export_chat(export_path: str, db_path: list[str], ft: list[str]):
conn = sqlite3.connect(db_path[0])
cur = conn.cursor()
msgs = get_msg(cur)
persons = get_person(db_path[1])
msgs = set_remark(persons, msgs)
store_p(export_path, msgs, persons, ft)
conn.close()
if __name__ == "__main__":
ME = 0 # 你的QQ号
ME_NAME = "" # 你的QQ昵称
LIMIT_LEN = 1000 # 限制导出的人数(这个是获取昵称,默认1000基本可以获取到大多数的昵称)
# 导出位置,数据库位置,导出格式
# export_chat("data/", ["nt_msg_1.clean.db","profile_info_1.clean.db"], ["txt", "json", "csv", "xml", "ddd"])
export_chat("data/", ["databases/nt_msg_1.clean.db", "databases/profile_info_1.clean.db"], ["ddd"])
396




被折叠的 条评论
为什么被折叠?



