core.entropy
Calculate Shannon entropy for byte buffers, windows, and streamed inputs.
- entropy_from_freq(freq, total)[source]
Compute Shannon entropy from byte frequency counts.
- Iterates over 256 frequency bins and applies the standard formula:
H = -sum(p * log2(p)) for each p = count / total where count > 0
- entropy_term_lut(total)[source]
lut[count] = p * math.log2(p)withp = count / total;lut[0] = 0.The per-bin terms of
entropy_from_freq(), computed with the same Python expression, so any sequential sum of them reproduces it bit for bit. Shared byentropy_from_freq_batch()andmemdiver.core.entropy_window.entropy_from_window_rows().
- entropy_from_freq_batch(counts, total)[source]
Vectorised
entropy_from_freq(), bit-identical row by row.countsis an(m, 256)matrix of non-negative histogram rows summing to at mosttotal. Each row’s result equalsentropy_from_freq(list(row), total)exactly (not merely to tolerance):per-count terms
p * math.log2(p)come from a lookup table built with the same Python expression (math.log2, notnp.log2);terms are accumulated strictly left-to-right over bins 0..255 with
np.cumsum(sequential, never pairwise), and zero bins contribute an exact0.0, matching theif count > 0skip;e -= tequals-(s + t)under sign-symmetric IEEE rounding, and a final+ 0.0maps the all-zero-0.0back to the reference0.0.
- shannon_entropy(data)[source]
Compute Shannon entropy of raw byte data.
Builds a full frequency table over the input and computes entropy in a single pass.
- HISTOGRAM_CHUNK_BYTES = 524288
Bytes histogrammed per chunk in
byte_histogram().bincountcasts its input tointpfirst, so one call over a whole 256 MiB dump allocated a 2 GiB index array; chunking bounds that copy at ~2 MiB. A multiple ofZERO_BLOCK_BYTES.
- ZERO_BLOCK_BYTES = 1024
All-zero blocks of this many bytes are counted without a
bincount(memory dumps are mostly zero pages: a 208 MiB lldb dump histograms ~15x faster). Must be a multiple of 8 (blocks are tested asuint64words).
- byte_histogram(data)[source]
256-bin
int64byte-value histogram of data (bytes-like or uint8).Exactly
np.bincount(data, minlength=256), faster and with bounded scratch. PerHISTOGRAM_CHUNK_BYTESchunk, all-zeroZERO_BLOCK_BYTESblocks are only counted; the remaining blocks are histogrammed as byte PAIRS (oneuint16bincount over 65536 bins), which halves the elements and spreads runs of equal bytes over more bins, and the pair table is folded back to bytes (each pair counts both of its bytes, so the fold does not depend on endianness).- Return type:
- entropy_from_byte_counts(counts, total)[source]
Shannon entropy (bits/byte) of a 256-bin histogram summing to total.
The float formula
shannon_entropy()has always used (np.log2over the nonzero probabilities, numpy pairwise sum), shared so a histogram accumulated slab by slab yields the same float as one whole-buffer call.
- compute_entropy_profile(data, window=32, step=1)[source]
Sliding-window entropy profile over byte data.
Vectorized with numpy. A
sliding_window_viewexposes every window as a row without copying; window positions are then processed in slabs ofCHUNK_POSITIONSrows. Each slab’s per-window 256-bin byte histogram is built in onenp.bincountover arow * 256 + bytecomposite key, and entropy is evaluated in the algebraically identical but reduction-friendly form:H = log2(window) - (1 / window) * sum_b count_b * log2(count_b)
The
0 * log0 = 0convention is handled by a per-count lookup table (flut[0] = 0), which also replaces millions oflog2evaluations with a cheap gather since counts are integers in[0, window]. This produces the same offsets and step semantics as the previous incremental pure-Python implementation, matching its output to within floating-point tolerance.The slab sums are now evaluated by
window_entropies(), which for windows up toSORTED_PATH_MAX_WINDOWtouches only the nonzero bins (O(window) instead of O(256) per position) while reproducing the 256-bin histogram form above bit for bit.For large dumps (e.g. 10 MB), use step=16 to produce ~625K sample points instead of ~10M.
- Parameters:
- Returns:
An
EntropyProfile– a read-only sequence of(offset, entropy)tuples (Pythonint/float), one per window position, backed by two numpy arrays (16 B/position instead of ~120 B for the formerlistof tuples). Use.as_arrays()for zero-copy(offsets, values)access. Empty when data is shorter than the window.- Return type:
EntropyProfile
- SORTED_SLAB_WINDOW_BYTES = 262144
Window bytes per slab of the sorted-run path in
window_entropies()(~45 B of scratch per window byte, so ~12 MiB per slab). Rows per slab are additionally capped atCHUNK_POSITIONS.
- SORTED_PATH_MAX_WINDOW = 32
Windows above this size take the 256-bin histogram path. The sorted-run path costs O(window) per position (one radix argsort), the histogram path O(256 + window) of cheaper passes; measured per position on heap-like / random data: window 16 ~180 vs ~400 ns, 32 ~330 vs ~450 ns, 48 even, 64+ the histogram wins.
- sorted_path_matches_numpy()[source]
Check whether
_count_log_sums_sorted()reproduces this numpy’s reduction.The sorted path mirrors numpy’s pairwise-summation layout; checked once per process on crafted rows (falls back to the histogram path if a future numpy ever reduces differently).
- Return type:
- window_entropies(arr, offsets, window)[source]
Entropy of the window-byte window at each offset of the uint8 arr.
The values of
compute_entropy_profile(), bit for bit, for any ascending in-rangeoffsets(rows are independent of each other and of the slab size). Scratch is one bounded slab.
- STREAM_SLAB_BYTES = 8388608
Bytes read per slab by
stream_entropy_profile().
- stream_entropy_profile(read, size, window=32, step=1, slab_bytes=None)[source]
(shannon_entropy(data), compute_entropy_profile(data, window, step))fordata = read(0, size), without ever holding data.read(offset, length) returns
data[offset:offset + length]. Bytes are read in slabs of slab_bytes (defaultSTREAM_SLAB_BYTES; +window - 1bytes of look-ahead so the windows starting in a slab are complete); each slab feeds the byte histogram and the profile positions that start inside it. Both results are bit-identical to the whole-buffer calls. Peak heap: one slab plus the output arrays (16 B per position).
- DEFAULT_ENTROPY_WINDOW = 32
The sliding window every entropy consumer defaults to (bytes).
- REFERENCE_ENTROPY_THRESHOLD = 4.5
The high-entropy threshold at
DEFAULT_ENTROPY_WINDOW– the oneEntropyScanAlgorithm.DEFAULT_THRESHOLDhas always used (“4.5 catches real crypto keys”). Single source of truth fordefault_entropy_threshold();entropy_scanreads it from here.
- max_window_entropy(window)[source]
Upper bound on the Shannon entropy (bits/byte) of one window-byte window.
log2(min(window, 256)): a window cannot hold more distinct byte values than it has bytes (all-distinct is the maximum,log2(window)), nor more than 256. Exact forwindow <= 256and for multiples of 256; a bound otherwise. 0.0 forwindow <= 1.
- random_window_entropy(window)[source]
Expected entropy (bits/byte) of a window-byte window of uniform random bytes.
Each byte value’s count is
Binomial(window, 1/256), soE[H] = log2(window) - (256 / window) * E[c * log2(c)], summed exactly overc = 0..window(O(window), cached). This is what real key material scores, and it stays well belowmax_window_entropy()near 256 bytes (7.18 vs 8.0 at 256): a window that small cannot fill 256 bins evenly.
- default_entropy_threshold(window=DEFAULT_ENTROPY_WINDOW)[source]
Window-aware default high-entropy threshold (bits/byte).
REFERENCE_ENTROPY_THRESHOLD(4.5) atDEFAULT_ENTROPY_WINDOW(32) – exactly, agreeing withentropy_scan– and the same fraction (~0.92) ofrandom_window_entropy()at every other window size. This scales the threshold by the expected entropy of a random window: 16 -> 3.63, 64 -> 5.31, 256 -> 6.61, 1024 -> 7.20.Scaling by the expected entropy of random data rather than by the achievable maximum (
max_window_entropy()) matters near 256 bytes: 0.9 * 8.0 = 7.2 atwindow=256is above the 7.18 a random window scores on average, so two thirds of the windows of a random key would miss it. The former fixed default, 7.5, is unreachable for any window below 182 bytes (2**7.5) – it reported nothing at the defaultwindow=32.
- threshold_is_reachable(threshold, window)[source]
Return true when the threshold is at or below the window’s entropy bound.
- find_high_entropy_regions(profile, threshold=None, min_width=32, window=DEFAULT_ENTROPY_WINDOW)[source]
Find contiguous high-entropy regions in an entropy profile.
Scans the profile for runs of consecutive points at or above the threshold, then filters by minimum width.
- Parameters:
profile (EntropyProfile | Sequence[Tuple[int, float]]) – Output of compute_entropy_profile (an EntropyProfile) or any sequence of (offset, entropy) tuples, assumed sorted by offset.
threshold (float | None) – Minimum entropy (bits/byte) to qualify as high-entropy.
None(the default) isdefault_entropy_threshold()of window (4.5 at the default 32-byte window). The former fixed default, 7.5, is unreachable for windows below 182 bytes; explicit values keep their meaning.min_width (int) – Minimum span (end - start) in bytes for a region to be reported. Default 32 (one AES-256 key length).
window (int) – The window size the profile was computed with; only used to derive the default threshold.
- Returns:
List of (start_offset, end_offset, mean_entropy) tuples for each qualifying region. Offsets refer to the window start positions from the profile. The region end is exclusive: the first below-threshold window start, or (for a run reaching the end of the profile) the last window start plus the profile step.
- Return type: