"""
Recover and reuse the DHTB-header keystream for Qualix (QLYX) signed FDL images.

Background: the first 0x200 bytes of a "signed" FDL are the standard DHTB
header (magic "DHTB", version=1 at offset 4, data_size at offset 0x30, rest
zero-padded) encrypted with a stream cipher whose keystream is reused
identically across different files (at least fdl1.bin and fdl2.bin from the
same burn). This lets you recover that keystream from any file whose true
size (and hence data_size) you can compute, and then decrypt/verify the
header of any other file encrypted the same way.

Usage:
    python3 recover_header_keystream.py fdl1.bin fdl2.bin [more_files.bin ...]
"""
import sys
import struct

HEADER_LEN = 0x200
SIGN_TYPE1_EXTRA = 0x2B4   # sign_type=1: 0x60 (sign_head) + 0x254 (sign_data)
SIGN_TYPE0_EXTRA = 0x294   # sign_type=0: 0x60 (sign_head) + 0x234 (sign_data)


def expected_plaintext_header(file_size, extra=SIGN_TYPE1_EXTRA):
    data_size = file_size - HEADER_LEN - extra
    pt = bytearray(HEADER_LEN)
    pt[0:4] = b"DHTB"
    pt[4:8] = struct.pack("<I", 1)
    pt[0x30:0x34] = struct.pack("<I", data_size)
    return bytes(pt), data_size


def recover_keystream(path, extra=SIGN_TYPE1_EXTRA):
    data = open(path, "rb").read()
    header_ct = data[:HEADER_LEN]
    pt, data_size = expected_plaintext_header(len(data), extra)
    ks = bytes(c ^ p for c, p in zip(header_ct, pt))
    return ks, data_size, header_ct


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return

    keystreams = []
    for path in sys.argv[1:]:
        ks, data_size, header_ct = recover_keystream(path)
        keystreams.append((path, ks))
        print(f"{path}: data_size=0x{data_size:x} (sign_type=1 hypothesis)")

    if len(keystreams) >= 2:
        base_path, base_ks = keystreams[0]
        for path, ks in keystreams[1:]:
            same = sum(1 for a, b in zip(base_ks, ks) if a == b)
            identical = ks == base_ks
            print(f"\nKeystream match {base_path} vs {path}: "
                  f"{'IDENTICAL' if identical else f'{same}/{HEADER_LEN} bytes match'}")

    print("\nRecovered keystream (hex, first file):")
    print(keystreams[0][1].hex())


if __name__ == "__main__":
    main()
