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

Parameters:
  • freq (list) – List of 256 integer counts (one per byte value).

  • total (int) – Sum of all counts (window size).

Returns:

Entropy in bits per byte, in range [0.0, 8.0]. Returns 0.0 when total is zero.

Return type:

float

entropy_term_lut(total)[source]

lut[count] = p * math.log2(p) with p = 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 by entropy_from_freq_batch() and memdiver.core.entropy_window.entropy_from_window_rows().

Parameters:

total (int)

Return type:

ndarray

entropy_from_freq_batch(counts, total)[source]

Vectorised entropy_from_freq(), bit-identical row by row.

counts is an (m, 256) matrix of non-negative histogram rows summing to at most total. Each row’s result equals entropy_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, not np.log2);

  • terms are accumulated strictly left-to-right over bins 0..255 with np.cumsum (sequential, never pairwise), and zero bins contribute an exact 0.0, matching the if count > 0 skip;

  • e -= t equals -(s + t) under sign-symmetric IEEE rounding, and a final + 0.0 maps the all-zero -0.0 back to the reference 0.0.

Parameters:
Return type:

ndarray

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.

Parameters:

data (bytes) – Arbitrary byte sequence.

Returns:

Entropy in bits per byte, in range [0.0, 8.0]. Returns 0.0 for empty input.

Return type:

float

HISTOGRAM_CHUNK_BYTES = 524288

Bytes histogrammed per chunk in byte_histogram(). bincount casts its input to intp first, so one call over a whole 256 MiB dump allocated a 2 GiB index array; chunking bounds that copy at ~2 MiB. A multiple of ZERO_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 as uint64 words).

byte_histogram(data)[source]

256-bin int64 byte-value histogram of data (bytes-like or uint8).

Exactly np.bincount(data, minlength=256), faster and with bounded scratch. Per HISTOGRAM_CHUNK_BYTES chunk, all-zero ZERO_BLOCK_BYTES blocks are only counted; the remaining blocks are histogrammed as byte PAIRS (one uint16 bincount 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:

ndarray

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.log2 over the nonzero probabilities, numpy pairwise sum), shared so a histogram accumulated slab by slab yields the same float as one whole-buffer call.

Parameters:
Return type:

float

compute_entropy_profile(data, window=32, step=1)[source]

Sliding-window entropy profile over byte data.

Vectorized with numpy. A sliding_window_view exposes every window as a row without copying; window positions are then processed in slabs of CHUNK_POSITIONS rows. Each slab’s per-window 256-bin byte histogram is built in one np.bincount over a row * 256 + byte composite 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 = 0 convention is handled by a per-count lookup table (flut[0] = 0), which also replaces millions of log2 evaluations 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 to SORTED_PATH_MAX_WINDOW touches 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:
  • data (bytes) – Raw memory dump bytes.

  • window (int) – Sliding window size in bytes (default 32).

  • step (int) – Advance step in bytes (default 1).

Returns:

An EntropyProfile – a read-only sequence of (offset, entropy) tuples (Python int/float), one per window position, backed by two numpy arrays (16 B/position instead of ~120 B for the former list of 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 at CHUNK_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:

bool

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-range offsets (rows are independent of each other and of the slab size). Scratch is one bounded slab.

Parameters:
Return type:

ndarray

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)) for data = read(0, size), without ever holding data.

read(offset, length) returns data[offset:offset + length]. Bytes are read in slabs of slab_bytes (default STREAM_SLAB_BYTES; + window - 1 bytes 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).

Parameters:
Return type:

Tuple[float, EntropyProfile]

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 one EntropyScanAlgorithm.DEFAULT_THRESHOLD has always used (“4.5 catches real crypto keys”). Single source of truth for default_entropy_threshold(); entropy_scan reads 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 for window <= 256 and for multiples of 256; a bound otherwise. 0.0 for window <= 1.

Parameters:

window (int)

Return type:

float

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), so E[H] = log2(window) - (256 / window) * E[c * log2(c)], summed exactly over c = 0..window (O(window), cached). This is what real key material scores, and it stays well below max_window_entropy() near 256 bytes (7.18 vs 8.0 at 256): a window that small cannot fill 256 bins evenly.

Parameters:

window (int)

Return type:

float

default_entropy_threshold(window=DEFAULT_ENTROPY_WINDOW)[source]

Window-aware default high-entropy threshold (bits/byte).

REFERENCE_ENTROPY_THRESHOLD (4.5) at DEFAULT_ENTROPY_WINDOW (32) – exactly, agreeing with entropy_scan – and the same fraction (~0.92) of random_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 at window=256 is 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 default window=32.

Parameters:

window (int)

Return type:

float

threshold_is_reachable(threshold, window)[source]

Return true when the threshold is at or below the window’s entropy bound.

Parameters:
Return type:

bool

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) is default_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:

List[Tuple[int, int, float]]