✨ 初始提交:月读第三方书源插件集合

每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit 9190db9019
38 files changed
+5783

No files matched your search

@@ -0,0 +1,240 @@
--[[--
番茄 reading API:registerkey / batch_full 请求构建与正文解密。
移植自 fanqie-re/fanqie_crypto.py + fanqie_request.encode_query。
@module koplugin.book.moonsource_fanqie.reading.crypto
--]]
local Aes = require("crypto.aes")
local Text = require("utils.text")
local Crypto = {}
local HARDCODED_KEY = Aes.from_hex("ac25c67ddd8f38c1b37a2348828e222e")
local AID = 1967
local function le64(n)
-- device_id 常是 19 位十进制串,超过 2^53,转成 Lua 数字会丢低位;串按 uint64 精确累加。
if type(n) == "string" and n:match("^%d+$") then
local ffi = require("ffi")
local v = ffi.new("uint64_t", 0)
for d in n:gmatch("%d") do v = v * 10 + tonumber(d) end
local out = {}
for i = 1, 8 do
out[i] = string.char(tonumber(v % 256))
v = v / 256
end
return table.concat(out)
end
n = tonumber(n) or 0
local out = {}
for i = 1, 8 do
out[i] = string.char(n % 256)
n = math.floor(n / 256)
end
return table.concat(out)
end
Crypto.urandom = require("utils.random").bytes
local function uuid_iv()
return (Aes.to_hex(Crypto.urandom(16)):sub(1, 16))
end
---@param device_id string|number
---@param user_id string|number|nil
---@param iv_text string|nil 16 ASCII chars
---@return string base64 content
function Crypto.build_register_content(device_id, user_id, iv_text)
local payload = le64(device_id) .. le64(user_id or 0)
iv_text = iv_text or uuid_iv()
assert(#iv_text == 16)
local iv = iv_text
local ct = Aes.cbc_encrypt(payload, HARDCODED_KEY, iv, true)
return Text.base64Encode(iv .. ct)
end
---@param encrypted_key_b64 string
---@return string v1_key uppercase hex
function Crypto.decrypt_server_key(encrypted_key_b64)
local raw = Text.base64Decode(encrypted_key_b64)
if #raw < 17 then error("encrypted key too short") end
local pt = Aes.cbc_decrypt(raw:sub(17), HARDCODED_KEY, raw:sub(1, 16), true)
return Aes.to_hex(pt):upper()
end
---@param encrypted_content_b64 string
---@param v1_key_hex string
---@return string binary
function Crypto.decrypt_content(encrypted_content_b64, v1_key_hex)
local raw = Text.base64Decode(encrypted_content_b64)
if #raw < 17 then error("encrypted content too short") end
local key = Aes.from_hex(v1_key_hex:lower())
return Aes.cbc_decrypt(raw:sub(17), key, raw:sub(1, 16), true)
end
--- 尽量解压 gzip/zlib;失败则原样返回。
---@param data string
---@param compress_status number|nil
---@return string
function Crypto.maybe_decompress(data, compress_status)
if not data or data == "" then return data end
local is_gzip = data:byte(1) == 0x1f and data:byte(2) == 0x8b
local is_zlib = data:byte(1) == 0x78
local need = (tonumber(compress_status) or 0) > 0 or is_gzip or is_zlib
if not need then return data end
--- 截断的载荷也要尽量给出前面解出的部分。
local function inflate(blob, window_bits)
return require("utils.inflate").all(blob, window_bits, true)
end
if is_gzip then
return inflate(data, 15 + 16) or inflate(data, 15 + 32) or data
end
if is_zlib then
return inflate(data, 15) or data
end
-- raw deflate
return inflate(data, -15) or data
end
---@param item table
---@param v1_key string
---@return string
function Crypto.decode_chapter_item(item, v1_key)
local content_str = item.content or item.origin_content or ""
if content_str == "" or content_str == "Invalid" then
return ""
end
local crypt_status = tonumber(item.crypt_status) or 0
local compress_status = tonumber(item.compress_status) or 0
local raw
if crypt_status == 0 and v1_key and v1_key ~= "" then
raw = Crypto.decrypt_content(content_str, v1_key)
else
raw = content_str
end
return Crypto.maybe_decompress(raw, compress_status)
end
---@param device table
---@param ts_ms number|nil
---@return table
function Crypto.build_common_query(device, ts_ms)
if type(ts_ms) ~= "number" then
ts_ms = os.time() * 1000
end
return {
iid = tostring(device.install_id),
device_id = tostring(device.device_id),
ac = "wifi",
channel = device.channel or "43536163a",
aid = tostring(AID),
app_name = "novelapp",
version_code = tostring(device.version_code or "73733"),
version_name = tostring(device.version_name or "7.3.7.33"),
device_platform = "android",
os = "android",
ssmix = "a",
device_type = device.device_type or "P30",
device_brand = device.device_brand or "Huawei",
language = device.language or "zh",
os_api = tostring(device.os_api or "30"),
os_version = tostring(device.os_version or "12"),
manifest_version_code = tostring(device.version_code or "73733"),
resolution = device.resolution or "1280*720",
dpi = tostring(device.dpi or "240"),
update_version_code = tostring(device.version_code or "73733"),
_rticket = tostring(ts_ms),
host_abi = device.host_abi or "armeabi-v7a",
cdid = device.cdid or "",
openudid = device.openudid or "",
}
end
---@param device table
---@param book_id string
---@param item_ids string[]
---@param ts_ms number|nil
---@return table
function Crypto.build_batch_full_query(device, book_id, item_ids, ts_ms)
local q = Crypto.build_common_query(device, ts_ms)
q.item_ids = table.concat(item_ids, ",")
q.key_register_ts = "0"
q.book_id = tostring(book_id)
q.req_type = "1"
return q
end
--- ByteDance query:item_ids 逗号、* / + 不 percent-encode。
---@param params table
---@return string
function Crypto.encode_query(params)
local order = {
"iid", "device_id", "ac", "channel", "aid", "app_name", "version_code",
"version_name", "device_platform", "os", "ssmix", "device_type", "device_brand",
"language", "os_api", "os_version", "manifest_version_code", "resolution",
"dpi", "update_version_code", "_rticket", "host_abi", "cdid", "openudid",
"item_ids", "key_register_ts", "book_id", "req_type",
}
local seen = {}
local parts = {}
local function add(k, v)
if v == nil or seen[k] then return end
seen[k] = true
local vs = tostring(v)
local ek = Text.urlEncode(tostring(k))
local ev
if k == "item_ids" then
ev = (Text.urlEncode(vs):gsub("%%2C", ","))
else
ev = Text.urlEncode(vs)
ev = ev:gsub("%%2A", "*"):gsub("%%2B", "+")
end
parts[#parts + 1] = ek .. "=" .. ev
end
for _idx, k in ipairs(order) do
if params[k] ~= nil then add(k, params[k]) end
end
for k, v in pairs(params) do
add(k, v)
end
return table.concat(parts, "&")
end
---@param device table
---@param ts_ms number|nil
---@return table
function Crypto.build_unsigned_headers(device, ts_ms)
ts_ms = ts_ms or (os.time() * 1000)
local vc = device.version_code or "73733"
local rom = tostring(device.rom_version or "S643.217451.03386707"):match("^[^%+]+") or ""
local ua = string.format(
"com.dragon.read.oversea.gp/%s (Linux; U; Android %s; zh_CN; %s; Build/%s;tt-ok/3.12.13.4-tiktok)",
vc, device.os_version or "12", device.device_type or "P30", rom)
local rnd = require("utils.random").hex(4)
return {
["User-Agent"] = ua,
["Accept"] = "application/json; charset=utf-8,application/x-protobuf",
["Accept-Encoding"] = "identity",
["sdk-version"] = "2",
["passport-sdk-version"] = "50564",
["lc"] = "101",
["x-tt-store-region"] = "cn-zj",
["x-tt-store-region-src"] = "did",
["x-vc-bdturing-sdk-version"] = "3.7.2.cn",
["x-xs-from-web"] = "0",
["X-Ss-Req-Ticket"] = tostring(ts_ms),
["x-reading-request"] = tostring(ts_ms) .. "-" .. rnd,
["Cookie"] = "store-region=cn-zj; store-region-src=did; install_id="
.. tostring(device.install_id),
}
end
Crypto.HARDCODED_KEY_HEX = "ac25c67ddd8f38c1b37a2348828e222e"
Crypto.HOST = "api5-normal-sinfonlinec.fqnovel.com"
Crypto.BATCH_FULL_PATH = "/reading/reader/batch_full/v"
Crypto.REGISTERKEY_PATH = "/reading/crypt/registerkey"
return Crypto
@@ -0,0 +1,274 @@
--[[--
番茄阅读设备身份:本机生成画像,经 device_register 换取 device_id/install_id。
禁止复用别人的 did;每台 KOReader 安装各自持久化一份。
@module koplugin.book.moonsource_fanqie.reading.device
--]]
local JSON = require("json")
local Request = require("http.request")
local Aes = require("crypto.aes")
local logger = require("utils.log")
local bit = require("bit")
local _ = require("l10n").get("moonsource_fanqie")
local Device = {}
local REGISTER_HOST = "log.snssdk.com"
local REGISTER_PATH = "/service/2/device_register/"
local TIMEOUT_RATIO = 2 / 3 -- × 「网络超时」,缺省 20 秒
-- 画像模板(不含服务端签发的 id)。
local PROFILE_TEMPLATE = {
channel = "43536163a",
version_code = "73733",
version_name = "7.3.7.33",
device_type = "P30",
device_brand = "HUAWEI",
language = "zh",
os_api = "31",
os_version = "12",
resolution = "1280*720",
dpi = "240",
host_abi = "arm64-v8a",
rom_version = "S643.217451.03386707",
}
local urandom = require("moonsource_fanqie.reading.crypto").urandom
local function uuid4()
local raw = urandom(16)
local b = { raw:byte(1, 16) }
b[7] = bit.bor(bit.band(b[7], 0x0f), 0x40)
b[9] = bit.bor(bit.band(b[9], 0x3f), 0x80)
return string.format(
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8],
b[9], b[10], b[11], b[12], b[13], b[14], b[15], b[16])
end
---@return table 本地画像(含 cdid/openudid,尚无 device_id)
function Device.newLocalProfile()
local out = {}
for k, v in pairs(PROFILE_TEMPLATE) do
out[k] = v
end
out.cdid = uuid4()
out.openudid = Aes.to_hex(urandom(8))
out.clientudid = uuid4()
return out
end
---@param src table|nil
---@return table|nil
function Device.normalize(src)
if type(src) ~= "table" then return nil end
local profile = type(src.device_profile) == "table" and src.device_profile or src
local device_id = tostring(src.device_id or "")
local install_id = tostring(src.install_id or "")
if device_id == "" or install_id == "" then
return nil
end
local out = Device.newLocalProfile()
for k in pairs(PROFILE_TEMPLATE) do
if profile[k] ~= nil and tostring(profile[k]) ~= "" then
out[k] = tostring(profile[k])
end
end
if profile.cdid and profile.cdid ~= "" then out.cdid = tostring(profile.cdid) end
if profile.openudid and profile.openudid ~= "" then out.openudid = tostring(profile.openudid) end
if profile.clientudid and profile.clientudid ~= "" then
out.clientudid = tostring(profile.clientudid)
elseif src.clientudid and src.clientudid ~= "" then
out.clientudid = tostring(src.clientudid)
end
out.device_id = device_id
out.install_id = install_id
out.version_code = tostring(out.version_code or PROFILE_TEMPLATE.version_code)
out.version_name = tostring(out.version_name or PROFILE_TEMPLATE.version_name)
return out
end
---@param settings FanqieSettings
---@param device table
local function persist(settings, device)
settings:set("reading_device", {
install_id = device.install_id,
device_id = device.device_id,
clientudid = device.clientudid,
device_profile = {
channel = device.channel,
version_code = device.version_code,
version_name = device.version_name,
device_type = device.device_type,
device_brand = device.device_brand,
language = device.language,
os_api = device.os_api,
os_version = device.os_version,
resolution = device.resolution,
dpi = device.dpi,
host_abi = device.host_abi,
cdid = device.cdid,
openudid = device.openudid,
rom_version = device.rom_version,
},
})
settings:flush()
end
---@param profile table
---@return string url, string body, table headers
local function buildRegisterRequest(profile)
local now = os.time() * 1000 + math.random(0, 999)
local openudid = profile.openudid
local cdid = profile.cdid
local qs = table.concat({
"ac=wifi",
"channel=" .. tostring(profile.channel),
"aid=1967",
"app_name=novelapp",
"version_code=" .. tostring(profile.version_code),
"version_name=" .. tostring(profile.version_name),
"device_platform=android",
"ssmix=a",
"device_type=" .. tostring(profile.device_type),
"device_brand=" .. tostring(profile.device_brand),
"language=" .. tostring(profile.language),
"os_api=" .. tostring(profile.os_api),
"os_version=" .. tostring(profile.os_version),
"openudid=" .. tostring(openudid),
"manifest_version_code=" .. tostring(profile.version_code),
"resolution=" .. tostring(profile.resolution),
"dpi=" .. tostring(profile.dpi),
"update_version_code=" .. tostring(profile.version_code),
"_rticket=" .. tostring(now),
"cdid=" .. tostring(cdid),
}, "&")
local body = {
magic_tag = "ss_app_log",
header = {
display_name = "番茄小说",
update_version_code = tonumber(profile.version_code) or 73733,
manifest_version_code = tonumber(profile.version_code) or 73733,
aid = 1967,
channel = profile.channel,
package = "com.dragon.read",
app_version = profile.version_name,
version_code = tonumber(profile.version_code) or 73733,
sdk_version = "3.7.2.cn",
os = "Android",
os_version = profile.os_version,
os_api = tonumber(profile.os_api) or 31,
device_model = profile.device_type,
device_brand = profile.device_brand,
device_manufacturer = profile.device_brand,
cpu_abi = profile.host_abi,
density_dpi = tonumber(profile.dpi) or 240,
resolution = (tostring(profile.resolution or "")):gsub("%*", "x"),
language = profile.language,
timezone = 8,
access = "wifi",
not_request_sender = 0,
rom_version = profile.rom_version,
cdid = cdid,
openudid = openudid,
clientudid = profile.clientudid or uuid4(),
region = "CN",
tz_name = "Asia/Shanghai",
tz_offset = 28800,
sim_region = "cn",
req_id = uuid4(),
apk_first_install_time = now - 86400000,
is_system_app = 0,
sdk_flavor = "china",
},
_gen_time = now,
}
local ua = string.format(
"com.dragon.read/%s (Linux; U; Android %s; zh_CN; %s; Build/%s;tt-ok/3.12.13.4-tiktok)",
profile.version_code, profile.os_version, profile.device_type,
tostring(profile.rom_version):match("^[^%+]+") or "S643")
return "https://" .. REGISTER_HOST .. REGISTER_PATH .. "?" .. qs,
JSON.encode(body),
{
["Content-Type"] = "application/json; charset=utf-8",
["User-Agent"] = ua,
["Accept-Encoding"] = "identity",
}
end
--- 向 log.snssdk.com 注册,拿到本机专属 device_id/install_id。
---@param settings FanqieSettings
---@param cb fun(device: table|nil, err: string|nil)
---@return CancelHandle
function Device.registerAsync(settings, cb)
local profile = Device.newLocalProfile()
local url, body, headers = buildRegisterRequest(profile)
return Request.request({
url = url,
method = "POST",
headers = headers,
body = body,
timeout = require("http.timeout").net(TIMEOUT_RATIO),
allow_redirects = true,
}, function(res, err)
-- turbo 超时仍返回 res 表,错误在 err;只看 res 会变成「HTTP nil」。
if err or not res then
local text = tostring(err or "")
if text:find("refused", 1, true) or text:find("Could not connect", 1, true) then
cb(nil, _("番茄正文需要注册设备,当前网络拦了 log.snssdk.com"))
return
end
cb(nil, err or _("番茄设备注册失败,请放行 log.snssdk.com"))
return
end
local code = tonumber(res.code)
if not Request.ok(code) then
cb(nil, "device_register HTTP " .. tostring(code))
return
end
local text = res.body or ""
if text == "" then
cb(nil, "device_register 空响应")
return
end
local ok, data = pcall(JSON.decode, text)
if not ok or type(data) ~= "table" then
cb(nil, "device_register 响应无效")
return
end
local device_id = tostring(data.device_id_str or data.device_id or "")
local install_id = tostring(data.install_id_str or data.install_id or "")
if device_id == "" or install_id == "" then
cb(nil, "device_register 未返回 device_id")
return
end
profile.device_id = device_id
profile.install_id = install_id
persist(settings, profile)
logger.info("fanqie device_register ok", "did=" .. device_id, "iid=" .. install_id)
cb(profile)
end)
end
--- 已有身份下一帧返回;否则异步注册。
--- 命中也必须异步:调用方在回调里换上后续请求的句柄,同步回调后再返回的句柄会把它覆盖掉。
---@param settings FanqieSettings
---@param cb fun(device: table|nil, err: string|nil)
---@return CancelHandle
function Device.ensureAsync(settings, cb)
local cached = Device.get(settings)
if cached then
return require("source.base").defer(cb, cached)
end
return Device.registerAsync(settings, cb)
end
--- 同步取已落盘身份;没有则返回 nil(调用方应走 ensureAsync)。
---@param settings FanqieSettings
---@return table|nil
function Device.get(settings)
return Device.normalize(settings:get("reading_device", nil))
end
return Device
@@ -0,0 +1,341 @@
--[[--
番茄四神签名:X-Khronos / X-Ladon / X-Helios / X-Argus。
移植自 fanqie-re/fanqie_sign.py。
@module koplugin.book.moonsource_fanqie.reading.sign
--]]
-- LuaJIT bit 的注解是 32 位 integer;这里传入的是 uint64 cdata 常量。
---@diagnostic disable: param-type-mismatch
local Aes = require("crypto.aes")
local Sm3 = require("crypto.sm3")
local Text = require("utils.text")
local md5 = require("ffi/sha2").md5
local ffi = require("ffi")
local bit = require("bit")
local Sign = {}
local AID = 1967
local LADON_AID = 3019
local LICENSE_ID = 1611921764
local SDK_VERSION_STR = "v04.04.05-ov-android"
local SDK_VERSION = 134744640
local SIGN_KEY = Aes.from_hex(
"ac1adaae95a7af94a5114ab3b3a97dd80050aa0a39314c40528caec95256c28c")
local INNER_SALT = string.char(0xf2, 0x81, 0x61, 0x6f)
-- Z 常量:LuaJIT 字符串 cast 不可靠,拆成高低 32 位拼。
local SIMON_Z = bit.bor(
ffi.cast("uint64_t", 0x046D678B),
bit.lshift(ffi.cast("uint64_t", 0x3DC94C3A), 32))
local function u64(n)
if type(n) == "cdata" then return n end
if type(n) == "string" then return ffi.cast("uint64_t", n) end
return ffi.cast("uint64_t", n)
end
local function u64_to_le(v)
local p = ffi.new("uint64_t[1]", v)
return ffi.string(p, 8)
end
local function le_to_u64(s)
local p = ffi.new("uint64_t[1]")
ffi.copy(p, s, 8)
return p[0]
end
local function ror64(v, n)
n = bit.band(n, 63)
v = u64(v)
if n == 0 then return v end
return bit.bor(bit.rshift(v, n), bit.lshift(v, 64 - n))
end
local function rol64(v, n)
n = bit.band(n, 63)
v = u64(v)
if n == 0 then return v end
return bit.bor(bit.lshift(v, n), bit.rshift(v, 64 - n))
end
local urandom = require("moonsource_fanqie.reading.crypto").urandom
local function pkcs7_pad(data, block)
return Aes.pkcs7_pad(data, block or 16)
end
-- ---------------------------------------------------------------------------
-- protobuf
-- ---------------------------------------------------------------------------
local function varint(v)
-- 无符号 32-bit:LuaJIT bit.* 对高位当有符号,不能直接 rshift。
if type(v) ~= "number" then v = tonumber(v) or 0 end
v = v % 0x100000000
if v < 0 then v = v + 0x100000000 end
local out = {}
while v >= 0x80 do
out[#out + 1] = string.char(bit.bor(bit.band(math.floor(v), 0x7f), 0x80))
v = math.floor(v / 128)
end
out[#out + 1] = string.char(v)
return table.concat(out)
end
local function pb_field(idx, wire, payload)
return varint(bit.bor(bit.lshift(idx, 3), wire)) .. payload
end
local function pb_varint(idx, val)
return pb_field(idx, 0, varint(val))
end
local function pb_bytes(idx, data)
return pb_field(idx, 2, varint(#data) .. data)
end
local function pb_str(idx, s)
return pb_bytes(idx, s)
end
-- ---------------------------------------------------------------------------
-- Ladon / Helios
-- ---------------------------------------------------------------------------
local function encrypt_ladon_block(hash_table, block)
local data0 = le_to_u64(block:sub(1, 8))
local data1 = le_to_u64(block:sub(9, 16))
for i = 0, 0x21 do
local h = le_to_u64(hash_table:sub(i * 8 + 1, i * 8 + 8))
data1 = bit.bxor(h, data0 + ror64(data1, 8))
data0 = bit.bxor(data1, ror64(data0, 0x3d))
end
return u64_to_le(data0) .. u64_to_le(data1)
end
local function build_ladon_hash_table(md5hex_ascii)
local table_buf = md5hex_ascii:sub(1, 32) .. string.rep("\0", 272 + 16 - 32)
local temp = {
le_to_u64(table_buf:sub(1, 8)),
le_to_u64(table_buf:sub(9, 16)),
le_to_u64(table_buf:sub(17, 24)),
le_to_u64(table_buf:sub(25, 32)),
}
local buffer_b0 = temp[1]
local buffer_b8 = temp[2]
-- drop first two; keep as queue
local queue = { temp[3], temp[4] }
local bytes = { table_buf:byte(1, #table_buf) }
for i = 0, 0x21 do
local x9 = buffer_b0
local x8 = ror64(buffer_b8, 8)
x8 = x8 + x9
x8 = bit.bxor(x8, u64(i))
queue[#queue + 1] = x8
x8 = bit.bxor(x8, ror64(x9, 61))
local le = u64_to_le(x8)
for j = 1, 8 do
bytes[(i + 1) * 8 + j] = le:byte(j)
end
buffer_b0 = x8
buffer_b8 = table.remove(queue, 1)
end
local out = {}
for i = 1, 272 + 16 do
out[i] = string.char(bytes[i] or 0)
end
return table.concat(out)
end
---@param khronos number
---@param random4 string|nil 4 bytes
---@return string base64
function Sign.encrypt_ladon(khronos, random4)
local data = string.format("%d-%d-%d", khronos, LICENSE_ID, LADON_AID)
random4 = random4 or urandom(4)
assert(#random4 == 4)
local keygen = random4 .. tostring(AID)
local table_ = build_ladon_hash_table(md5(keygen))
local padded = pkcs7_pad(data, 16)
local enc = {}
for i = 1, #padded, 16 do
enc[#enc + 1] = encrypt_ladon_block(table_, padded:sub(i, i + 15))
end
return Text.base64Encode(random4 .. table.concat(enc))
end
-- ---------------------------------------------------------------------------
-- Argus
-- ---------------------------------------------------------------------------
local function derive_inner_key()
return Sm3.hash(SIGN_KEY .. INNER_SALT .. SIGN_KEY)
end
local function simon_key_expansion(key4)
local key = {}
for i = 1, 4 do key[i] = key4[i] end
for i = 5, 72 do
local tmp = bit.bxor(ror64(key[i - 1], 3), key[i - 3])
tmp = bit.bxor(tmp, ror64(tmp, 1))
-- key 下标从 1 起:Lua 的 i=5 对应参考实现的第 4 个轮密钥,z 序列位为 (i-5)%62。
local bit_i = bit.band(bit.rshift(SIMON_Z, (i - 5) % 62), u64(1))
local not_prev = bit.bnot(key[i - 4])
key[i] = bit.bxor(bit.bxor(bit.bxor(not_prev, tmp), bit_i), u64(3))
end
return key
end
local function simon_encrypt_block(block, round_keys)
local x_i = le_to_u64(block:sub(1, 8))
local x_i1 = le_to_u64(block:sub(9, 16))
for i = 1, 72 do
local rk = round_keys[i]
local tmp = x_i1
local f = bit.band(rol64(x_i1, 1), rol64(x_i1, 8))
x_i1 = bit.bxor(bit.bxor(bit.bxor(x_i, f), rol64(x_i1, 2)), rk)
x_i = tmp
end
return u64_to_le(x_i) .. u64_to_le(x_i1)
end
local function simon_encrypt(data, key32)
assert(#data % 16 == 0 and #key32 == 32)
local key4 = {
le_to_u64(key32:sub(1, 8)),
le_to_u64(key32:sub(9, 16)),
le_to_u64(key32:sub(17, 24)),
le_to_u64(key32:sub(25, 32)),
}
local rks = simon_key_expansion(key4)
local out = {}
for i = 1, #data, 16 do
out[#out + 1] = simon_encrypt_block(data:sub(i, i + 15), rks)
end
return table.concat(out)
end
local function get_bodyhash(stub_hex)
local raw
if stub_hex and stub_hex ~= "" then
local ok, decoded = pcall(Aes.from_hex, stub_hex)
raw = ok and decoded or string.rep("\0", 16)
else
raw = string.rep("\0", 16)
end
return Sm3.hash(raw):sub(1, 6)
end
local function get_queryhash(query)
if query and query ~= "" then
return Sm3.hash(query):sub(1, 6)
end
return Sm3.hash(string.rep("\0", 16)):sub(1, 6)
end
local function encrypt_enc_pb(data, length)
local d = { data:byte(1, #data) }
local xor_array = { unpack(d, 1, 8) }
for i = 9, length do
d[i] = bit.bxor(d[i], xor_array[((i - 1) % 8) + 1])
end
local rev = {}
for i = length, 1, -1 do
rev[#rev + 1] = string.char(d[i])
end
return table.concat(rev)
end
local function u32_shl(v, n)
-- bit.lshift 对 >2^30 的值会按有符号 32 位溢出;用乘法保 uint32。
v = bit.band(v, 0xffffffff)
for _step = 1, n do
v = bit.band(v * 2, 0xffffffff)
end
return v
end
---@param query string
---@param timestamp number unix seconds (khronos)
---@param device_id string
---@param opts table|nil
---@return string base64
function Sign.encrypt_argus(query, timestamp, device_id, opts)
opts = opts or {}
local version_name = opts.version_name or "7.3.7.33"
local aid = opts.aid or AID
local device_type = opts.device_type or "P30"
local os_version = opts.os_version or "12"
local rand_val = opts.rand_val
if not rand_val then
local r = urandom(4)
rand_val = bit.band(
bit.bor(bit.lshift(r:byte(1), 24), bit.lshift(r:byte(2), 16),
bit.lshift(r:byte(3), 8), r:byte(4)),
0x7fffffff)
end
local pb = table.concat({
pb_varint(1, u32_shl(0x20200929, 1)),
pb_varint(2, 2),
pb_varint(3, rand_val),
pb_str(4, tostring(aid)),
pb_str(5, tostring(device_id)),
pb_str(6, tostring(LICENSE_ID)),
pb_str(7, version_name),
pb_str(8, SDK_VERSION_STR),
pb_varint(9, SDK_VERSION),
pb_bytes(10, string.rep("\0", 8)),
pb_varint(11, 0),
pb_varint(12, u32_shl(timestamp, 1)),
pb_bytes(13, get_bodyhash(opts.body_stub)),
pb_bytes(14, get_queryhash(query)),
pb_varint(20, 738),
pb_bytes(23, table.concat({
pb_str(1, device_type),
pb_str(2, os_version),
pb_str(3, "googleplay"),
pb_varint(4, 0x48000000),
})),
})
local padded = pkcs7_pad(pb, 16)
local enc_pb = simon_encrypt(padded, derive_inner_key())
local prefix = string.char(0xf2, 0xf7, 0xfc, 0xff, 0xf2, 0xf7, 0xfc, 0xff)
local inner = encrypt_enc_pb(prefix .. enc_pb, #enc_pb + 8)
local head = string.char(0xa6, 0x6e, 0xad, 0x9f, 0x77, 0x01, 0xd0, 0x0c, 0x18)
local buf = head .. inner .. "ao"
local aes_key = Aes.from_hex(md5(SIGN_KEY:sub(1, 16)))
local aes_iv = Aes.from_hex(md5(SIGN_KEY:sub(17, 32)))
local encrypted = Aes.cbc_encrypt(buf, aes_key, aes_iv, true)
return Text.base64Encode(string.char(0xf2, 0x81) .. encrypted)
end
---@param query_string string
---@param device_id string
---@param opts table|nil
---@return table headers
function Sign.sign_headers(query_string, device_id, opts)
opts = opts or {}
local khronos = opts.khronos or os.time()
return {
["X-Khronos"] = tostring(khronos),
["X-Ladon"] = Sign.encrypt_ladon(khronos, opts.ladon_random4),
-- X-Helios 与 X-Ladon 同一算法,只是随机数独立。
["X-Helios"] = opts.helios or Sign.encrypt_ladon(khronos, opts.helios_random4),
["X-Argus"] = Sign.encrypt_argus(query_string, khronos, device_id, {
version_name = opts.version_name,
device_type = opts.device_type,
os_version = opts.os_version,
rand_val = opts.rand_val,
}),
}
end
Sign.derive_inner_key = derive_inner_key
return Sign