"""Pure-Python pieces of the KWF `kwpsec.getData` algorithm. This module is intentionally incremental. The first closed slice is the VM function at 9756..9942, which converts a JS string into a byte-string using UTF-16 code units and a classic UTF-8-like encoder. """ from __future__ import annotations import math from collections.abc import Mapping from typing import Any KWF_FINGERPRINT_KEYS = tuple(f"k{idx}" for idx in range(1, 15)) KWF_BASE64_ALPHABET = ( "ZmserbBoHQtNP+wOcza/LpngG8yJq42KWYj0DSfdikx3VT16IlUAFM97hECvuRX5" ) KWF_AES_IV = b"mhaqhnjmr0rsoo3o" KWF_OBFUSCATED_KEY_GRID = ( (-2002111551, 1077744408, -672376612, 419994569), (528185349, -425267957, 826979799, -102918898), (-1176467946, -1009525813, -1747891260, -5343550), (1903666895, 811678054, 1999858998, 1902537836), (845440362, 1915501381, 85939827, 1954101791), (1176330101, -723278305, -771952532, -1517958541), (-476539642, -1765160690, 1194670434, -491719919), (19424791, -1426441870, -305201136, 260043521), (240620822, -506429735, 203390665, 56659400), (221714654, 1534944014, 1466047943, 1409454095), (1496680657, -1917231675, -623165438, -1898328051), ) KWF_AES_SEED = 14 _AES_SBOX = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53,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0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, ) def js_utf16_code_units(text: str) -> list[int]: """Return JavaScript `charCodeAt`-style UTF-16 code units.""" raw = text.encode("utf-16-le", errors="surrogatepass") return [ raw[idx] | (raw[idx + 1] << 8) for idx in range(0, len(raw), 2) ] def kwf_string_encoder_bytes(text: str) -> bytes: """Port of KWF VM slice 9756..9942. The original VM iterates JavaScript `charCodeAt` units. It emits: - ASCII code units 1..127 as-is; - code units 128..2047 as two bytes; - code units above 2047 as three bytes. Code unit 0 intentionally falls through to the two-byte branch, matching the VM's `code >= 1 && code <= 127` ASCII condition. """ out = bytearray() for code in js_utf16_code_units(text): if 1 <= code <= 0x7F: out.append(code) elif code > 0x7FF: out.append(0xE0 | ((code >> 12) & 0x0F)) out.append(0x80 | ((code >> 6) & 0x3F)) out.append(0x80 | (code & 0x3F)) else: out.append(0xC0 | ((code >> 6) & 0x1F)) out.append(0x80 | (code & 0x3F)) return bytes(out) def kwf_string_encoder_binary(text: str) -> str: """Return the VM's JavaScript byte-string representation.""" return "".join(chr(item) for item in kwf_string_encoder_bytes(text)) def kwf_mixer_permutation(total: int, seed: float) -> list[int]: """Port the index shuffle from KWF VM slice 8889..9050. The VM builds ``Array(total).fill().map((_, index) => index)`` and then swaps from the end using ``Math.floor((i * this._seed) % (i + 1))``. """ if total < 0: raise ValueError("total must be non-negative") items = list(range(total)) for idx in range(total - 1, 0, -1): swap_idx = math.floor((idx * seed) % (idx + 1)) if swap_idx < 0 or swap_idx > idx: raise ValueError("seed produced an invalid swap index") items[idx], items[swap_idx] = items[swap_idx], items[idx] return items def kwf_mixer_char(key_grid: list[str] | tuple[str, ...], seed: float, row: int, col: int) -> str: """Return ``this._Ke[floor(pos / width)][pos % width]`` after shuffle. ``row`` and ``col`` are the original coordinates. The shuffled array maps original flat indexes to output positions, then the output position selects the final character from ``_Ke``. """ if not key_grid: raise ValueError("key_grid must not be empty") width = len(key_grid[0]) if width == 0: raise ValueError("key_grid rows must not be empty") if any(len(item) != width for item in key_grid): raise ValueError("key_grid rows must have the same length") height = len(key_grid) if row < 0 or row >= height or col < 0 or col >= width: raise IndexError("row or col out of range") target = row * width + col permutation = kwf_mixer_permutation(height * width, seed) position = permutation.index(target) return key_grid[position // width][position % width] def _kwf_mixer_value( grid: tuple[tuple[int, ...], ...], seed: float, row: int, col: int, ) -> int: width = len(grid[0]) target = row * width + col permutation = kwf_mixer_permutation(len(grid) * width, seed) position = permutation.index(target) return grid[position // width][position % width] & 0xFFFFFFFF def kwf_aes_key_bytes() -> bytes: """Recover the fixed AES key hidden behind the `_Ke` mixer.""" words = [ _kwf_mixer_value(KWF_OBFUSCATED_KEY_GRID, KWF_AES_SEED, 0, col) for col in range(4) ] return b"".join(word.to_bytes(4, "big") for word in words) def _aes_xtime(value: int) -> int: return (((value << 1) ^ 0x1B) & 0xFF) if value & 0x80 else (value << 1) & 0xFF def _aes_mix_column(col: list[int]) -> None: total = col[0] ^ col[1] ^ col[2] ^ col[3] first = col[0] col[0] ^= total ^ _aes_xtime(col[0] ^ col[1]) col[1] ^= total ^ _aes_xtime(col[1] ^ col[2]) col[2] ^= total ^ _aes_xtime(col[2] ^ col[3]) col[3] ^= total ^ _aes_xtime(col[3] ^ first) def _aes_expand_key(key: bytes) -> list[list[int]]: if len(key) != 16: raise ValueError("AES-128 key must be 16 bytes") words = [list(key[idx: idx + 4]) for idx in range(0, 16, 4)] for idx in range(4, 44): temp = words[idx - 1].copy() if idx % 4 == 0: temp = temp[1:] + temp[:1] temp = [_AES_SBOX[item] for item in temp] temp[0] ^= _AES_RCON[idx // 4] words.append([left ^ right for left, right in zip(words[idx - 4], temp)]) return [sum(words[4 * round_idx: 4 * round_idx + 4], []) for round_idx in range(11)] def _aes_encrypt_block(block: bytes, key: bytes) -> bytes: if len(block) != 16: raise ValueError("AES block must be 16 bytes") state = list(block) round_keys = _aes_expand_key(key) def add_round_key(round_idx: int) -> None: for idx, item in enumerate(round_keys[round_idx]): state[idx] ^= item def sub_bytes() -> None: for idx, item in enumerate(state): state[idx] = _AES_SBOX[item] def shift_rows() -> None: state[1], state[5], state[9], state[13] = state[5], state[9], state[13], state[1] state[2], state[6], state[10], state[14] = state[10], state[14], state[2], state[6] state[3], state[7], state[11], state[15] = state[15], state[3], state[7], state[11] def mix_columns() -> None: for col_idx in range(4): start = col_idx * 4 col = state[start: start + 4] _aes_mix_column(col) state[start: start + 4] = col add_round_key(0) for round_idx in range(1, 10): sub_bytes() shift_rows() mix_columns() add_round_key(round_idx) sub_bytes() shift_rows() add_round_key(10) return bytes(state) def _aes_gmul(left: int, right: int) -> int: """Multiply two bytes in AES' GF(2^8).""" result = 0 for _ in range(8): if right & 1: result ^= left high_bit = left & 0x80 left = (left << 1) & 0xFF if high_bit: left ^= 0x1B right >>= 1 return result def _aes_inv_mix_column(col: list[int]) -> None: first, second, third, fourth = col col[0] = ( _aes_gmul(first, 0x0E) ^ _aes_gmul(second, 0x0B) ^ _aes_gmul(third, 0x0D) ^ _aes_gmul(fourth, 0x09) ) col[1] = ( _aes_gmul(first, 0x09) ^ _aes_gmul(second, 0x0E) ^ _aes_gmul(third, 0x0B) ^ _aes_gmul(fourth, 0x0D) ) col[2] = ( _aes_gmul(first, 0x0D) ^ _aes_gmul(second, 0x09) ^ _aes_gmul(third, 0x0E) ^ _aes_gmul(fourth, 0x0B) ) col[3] = ( _aes_gmul(first, 0x0B) ^ _aes_gmul(second, 0x0D) ^ _aes_gmul(third, 0x09) ^ _aes_gmul(fourth, 0x0E) ) def _aes_decrypt_block(block: bytes, key: bytes) -> bytes: if len(block) != 16: raise ValueError("AES block must be 16 bytes") state = list(block) round_keys = _aes_expand_key(key) def add_round_key(round_idx: int) -> None: for idx, item in enumerate(round_keys[round_idx]): state[idx] ^= item def inv_sub_bytes() -> None: for idx, item in enumerate(state): state[idx] = _AES_INV_SBOX[item] def inv_shift_rows() -> None: state[1], state[5], state[9], state[13] = state[13], state[1], state[5], state[9] state[2], state[6], state[10], state[14] = state[10], state[14], state[2], state[6] state[3], state[7], state[11], state[15] = state[7], state[11], state[15], state[3] def inv_mix_columns() -> None: for col_idx in range(4): start = col_idx * 4 col = state[start: start + 4] _aes_inv_mix_column(col) state[start: start + 4] = col add_round_key(10) for round_idx in range(9, 0, -1): inv_shift_rows() inv_sub_bytes() add_round_key(round_idx) inv_mix_columns() inv_shift_rows() inv_sub_bytes() add_round_key(0) return bytes(state) def _pkcs7_pad(data: bytes, block_size: int = 16) -> bytes: pad = block_size - (len(data) % block_size) return data + bytes([pad]) * pad def _pkcs7_unpad(data: bytes, block_size: int = 16) -> bytes: if not data or len(data) % block_size: raise ValueError("PKCS7 data length must be a positive block multiple") pad = data[-1] if pad < 1 or pad > block_size: raise ValueError("invalid PKCS7 padding length") if data[-pad:] != bytes([pad]) * pad: raise ValueError("invalid PKCS7 padding bytes") return data[:-pad] def kwf_aes_cbc_encrypt( data: bytes, key: bytes | None = None, iv: bytes = KWF_AES_IV, ) -> bytes: """AES-CBC used by the KWF fingerprint tail.""" key = kwf_aes_key_bytes() if key is None else key if len(iv) != 16: raise ValueError("AES-CBC IV must be 16 bytes") padded = _pkcs7_pad(data) out = bytearray() previous = iv for idx in range(0, len(padded), 16): block = bytes(left ^ right for left, right in zip(padded[idx: idx + 16], previous)) encrypted = _aes_encrypt_block(block, key) out.extend(encrypted) previous = encrypted return bytes(out) def kwf_aes_cbc_decrypt( data: bytes, key: bytes | None = None, iv: bytes = KWF_AES_IV, ) -> bytes: """AES-CBC/PKCS7 decrypt used by WebWeapon/KWF-compatible payloads.""" key = kwf_aes_key_bytes() if key is None else key if len(key) != 16: raise ValueError("AES-128 key must be 16 bytes") if len(iv) != 16: raise ValueError("AES-CBC IV must be 16 bytes") if len(data) == 0 or len(data) % 16: raise ValueError("AES-CBC ciphertext length must be a positive block multiple") out = bytearray() previous = iv for idx in range(0, len(data), 16): block = bytes(data[idx: idx + 16]) decrypted = _aes_decrypt_block(block, key) out.extend(left ^ right for left, right in zip(decrypted, previous)) previous = block return _pkcs7_unpad(bytes(out)) def kwf_encrypt_fingerprint_hex(plain: str) -> str: """Encrypt the local100 fingerprint string and return KWF lowercase hex.""" return kwf_aes_cbc_encrypt(plain.encode("utf-8")).hex() def kwf_pack_fingerprint_plain( plain: str, alg_version: str = "0", key_version: str = "0", ) -> str: encrypted_hex = kwf_encrypt_fingerprint_hex(plain) encoded = kwf_base64_encode_bytes(encrypted_hex.encode("ascii")) return kwf_insert_version_fields(encoded, alg_version, key_version) def kwf_pack_fingerprint_fields( fields: Mapping[str, Any], alg_version: str = "0", key_version: str = "0", ) -> str: return kwf_pack_fingerprint_plain( kwf_fingerprint_plain(fields), alg_version=alg_version, key_version=key_version, ) def kwf_default_fingerprint_fields( collect_count: int | str, now_ms: int, language: str = "zh-CN", k10: int = 60, k11: int = 508, ) -> dict[str, Any]: """Build the current KWF default environment fingerprint fields. These values match the local WebView stubs used by `core/h5_kww_server.mjs` and the active Nebula `PnGU...` branch. `collect_count` is the value read from `localStorage.kwfcv1` before it is incremented. """ return { "k1": 1, "k2": "0.0.2", "k3": language, "k4": "0", "k5": False, "k6": True, "k7": True, "k8": "1", "k9": "0", "k10": k10, "k11": k11, "k12": int(now_ms), "k13": str(collect_count), "k14": "", } def kwf_generate_kww( collect_count: int | str, now_ms: int, language: str = "zh-CN", ) -> str: return kwf_pack_fingerprint_fields( kwf_default_fingerprint_fields( collect_count=collect_count, now_ms=now_ms, language=language, ) ) def _js_fingerprint_value(value: Any) -> str: if value is None: return "" if isinstance(value, bool): return "1" if value else "0" return str(value) def kwf_fingerprint_plain( fields: Mapping[str, Any], keys: tuple[str, ...] = KWF_FINGERPRINT_KEYS, ) -> str: """Port the KWF local100/local91 plain fingerprint join. The VM builds ``["k1", ..., "k14"]``, maps values from an Object.assign result, coerces booleans to ``"1"``/``"0"``, and joins with ``"|"``. Missing/``undefined`` values become empty fields under JavaScript join semantics. """ return "|".join(_js_fingerprint_value(fields.get(key)) for key in keys) def kwf_insert_version_fields( encoded_ciphertext: str, alg_version: str = "0", key_version: str = "0", ) -> str: """Port the visible packaging part of KWF VM slice 9959..10210. After encryption/base64, the VM inserts ``ALG_VERSION`` after ten characters and ``KEY_VERSION`` after the next five characters. """ return ( encoded_ciphertext[:10] + alg_version + encoded_ciphertext[10:15] + key_version + encoded_ciphertext[15:] ) def kwf_remove_version_fields(packed: str) -> tuple[str, str, str]: """Reverse ``kwf_insert_version_fields`` for analysis/parity checks.""" if len(packed) < 17: raise ValueError("packed text is too short to contain version fields") return packed[:10] + packed[11:16] + packed[17:], packed[10], packed[16] def kwf_base64_encode_bytes( data: bytes | bytearray | memoryview, alphabet: str = KWF_BASE64_ALPHABET, ) -> str: """Port KWF VM slice 9509..9755. This is standard 3-byte to 4-character base64 packing, but with KWF's custom alphabet from local[44]. """ raw = bytes(data) if len(alphabet) != 64: raise ValueError("alphabet must contain exactly 64 characters") out: list[str] = [] for idx in range(0, len(raw), 3): chunk = raw[idx : idx + 3] b0 = chunk[0] if len(chunk) == 1: out.append(alphabet[b0 >> 2]) out.append(alphabet[(b0 & 0x03) << 4]) out.append("=") out.append("=") elif len(chunk) == 2: b1 = chunk[1] out.append(alphabet[b0 >> 2]) out.append(alphabet[((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4)]) out.append(alphabet[(b1 & 0x0F) << 2]) out.append("=") else: b1 = chunk[1] b2 = chunk[2] out.append(alphabet[b0 >> 2]) out.append(alphabet[((b0 & 0x03) << 4) | ((b1 & 0xF0) >> 4)]) out.append(alphabet[((b1 & 0x0F) << 2) | ((b2 & 0xC0) >> 6)]) out.append(alphabet[b2 & 0x3F]) return "".join(out) def kwf_base64_decode_bytes( text: str, alphabet: str = KWF_BASE64_ALPHABET, ) -> bytes: """Decode the KWF custom-alphabet base64 form.""" if len(alphabet) != 64: raise ValueError("alphabet must contain exactly 64 characters") if len(text) % 4 != 0: raise ValueError("base64 text length must be a multiple of 4") lookup = {ch: idx for idx, ch in enumerate(alphabet)} out = bytearray() for idx in range(0, len(text), 4): block = text[idx : idx + 4] pad = block.count("=") if pad and block[-pad:] != "=" * pad: raise ValueError("padding is only valid at the end of a block") values = [lookup[ch] if ch != "=" else 0 for ch in block] out.append((values[0] << 2) | (values[1] >> 4)) if pad < 2: out.append(((values[1] & 0x0F) << 4) | (values[2] >> 2)) if pad < 1: out.append(((values[2] & 0x03) << 6) | values[3]) return bytes(out) __all__ = [ "KWF_BASE64_ALPHABET", "KWF_AES_IV", "KWF_AES_SEED", "KWF_FINGERPRINT_KEYS", "KWF_OBFUSCATED_KEY_GRID", "js_utf16_code_units", "kwf_aes_cbc_encrypt", "kwf_aes_cbc_decrypt", "kwf_aes_key_bytes", "kwf_base64_decode_bytes", "kwf_base64_encode_bytes", "kwf_default_fingerprint_fields", "kwf_encrypt_fingerprint_hex", "kwf_fingerprint_plain", "kwf_generate_kww", "kwf_insert_version_fields", "kwf_mixer_char", "kwf_mixer_permutation", "kwf_pack_fingerprint_fields", "kwf_pack_fingerprint_plain", "kwf_remove_version_fields", "kwf_string_encoder_binary", "kwf_string_encoder_bytes", ]