Entropy Profiles: Compressed, Encrypted or Packed?
Strings and Entropy defined Shannon entropy and showed that compressed and encrypted data both score close to 8 bits per byte. A malware analyst uses entropy in three recurring situations: a sample with a high-entropy section (packed? encrypted configuration? just a compressed image resource?), a file server full of files that suddenly score near 8 (ransomware, or a backup job?), and a document whose header is normal but whose body is not. This lesson adds the tools to answer them: entropy profiles over a file, the effect of the window size, a statistical test that separates compressed from random-looking data, and partial encryption.
A profile, not a number
One entropy value for a whole file averages everything together. A profile, the entropy of a window sliding through the file, shows where the structure is. The lab draws profiles of four synthetic 32 KiB files (generated from a fixed seed; no real samples): a document with an embedded archive, a packed executable, a file whose regions were replaced by random bytes the way ransomware output looks, and a plain text log.
Things to try:
- Packed executable (the default): a low header, a code region around 6 bits per byte, then a long plateau near 8 where the packed data sits. A stub of normal code followed by a high plateau is the classic shape of a packed file (Packing).
- Window size: set the window to 256 bytes. The plateau drops to about 7.2 and the threshold starts flagging and unflagging windows at random. With bytes, random data cannot fill all 256 byte values evenly, so the measured entropy is below 8; at it is about 7.95. Thresholds only make sense together with the window size.
- Document with an archive: the compressed part is high too. Entropy alone does not tell compressed from encrypted.
Definitions
- Entropy profile: computed over windows of bytes at a step (here 256), plotted against the offset.
- Chi-square statistic of the byte histogram against the uniform distribution, for bytes with counts :
For truly uniform random bytes it follows a chi-square distribution with 255 degrees of freedom: mean 255, standard deviation . Good ciphertext behaves like that. Compressed data (deflate, LZMA) is nearly uniform but keeps small biases, so over tens of kilobytes its is far larger. Entropy measures how spread out the histogram is; measures how far it is from perfectly flat, and is much more sensitive near the top.
- Intermittent (partial) encryption: modern ransomware often encrypts only part of each file (every -th block, or the first megabytes) to go faster. The whole-file entropy can stay moderate while every encrypted block is near 8.
Separating compressed from random-looking data
The example compares text, the same text compressed with zlib, and random bytes (standing in for ciphertext; real code would draw keys from secrets), each 190,650 bytes long, with both measures:
import math, random, zlib
from collections import Counter
def entropy(d):
n = len(d)
return -sum(c / n * math.log2(c / n) for c in Counter(d).values())
def chi2(d):
n, counts = len(d), Counter(d)
e = n / 256
return sum((counts.get(i, 0) - e) ** 2 / e for i in range(256))
r = random.Random(42)
words = "invoice report total quarter north south sales review customer order meeting notes".split()
text = " ".join(f"{r.choice(words)} {r.randrange(10000)}" for _ in range(60000)).encode()
compressed = zlib.compress(text, 9)
rand = r.randbytes(len(compressed))
print(f"{'data':<12} {'bytes':>7} {'H bits/byte':>12} {'chi2':>10}")
for name, d in [("text", text[:len(compressed)]), ("zlib", compressed), ("random", rand)]:
print(f"{name:<12} {len(d):>7} {entropy(d):>12.4f} {chi2(d):>10.1f}")
print("uniform random: chi2 mean 255, sd", round(math.sqrt(2 * 255), 1))data bytes H bits/byte chi2
text 190650 4.4615 2832974.7
zlib 190650 7.9967 889.5
random 190650 7.9991 228.7
uniform random: chi2 mean 255, sd 22.6
The entropy of the compressed data and of the random data differ only in the third or fourth decimal, which no threshold can use reliably. The chi-square values are far apart: the random bytes land close to 255, as theory says, while the zlib stream lands many standard deviations above it. That is why some ransomware detectors and triage tools add a chi-square (or a similar randomness test) to entropy. It is a statistical hint: short inputs, other compressors (LZMA, Zstandard, encrypted archives that really are random) and encodings change the picture, so it is one feature among several.
Partial encryption in a file profile
The second example builds a synthetic 64 KiB "document" and simulates two kinds of ransomware output, with random bytes standing in for ciphertext: the whole body replaced, or only every other 4 KiB block. It prints whole-file entropy and the share of 4 KiB blocks above 7.9 bits per byte.
import math, random
from collections import Counter
def entropy(d):
n = len(d)
return -sum(c / n * math.log2(c / n) for c in Counter(d).values())
r = random.Random(7)
words = b"the of and to quarter report sales customer invoice meeting notes north south total".split()
doc = b"LABDOC1\0" + b" ".join(r.choice(words) for _ in range(20000))[:65536 - 8]
BLOCK = 4096
def full(d): return d[:8] + r.randbytes(len(d) - 8) # header kept, body replaced
def every_other(d):
out = bytearray(d)
for off in range(0, len(d), 2 * BLOCK):
out[off:off + BLOCK] = r.randbytes(min(BLOCK, len(d) - off))
return bytes(out)
for name, d in [("original", doc), ("fully replaced", full(doc)), ("every other block", every_other(doc))]:
blocks = [entropy(d[o:o + BLOCK]) for o in range(0, len(d), BLOCK)]
high = sum(h > 7.9 for h in blocks)
print(f"{name:<18} whole file H = {entropy(d):.2f} blocks > 7.9: {high:2d}/{len(blocks)} "
+ "".join("#" if h > 7.9 else "." for h in blocks))original whole file H = 3.82 blocks > 7.9: 0/16 ................
fully replaced whole file H = 8.00 blocks > 7.9: 16/16 ################
every other block whole file H = 6.73 blocks > 7.9: 8/16 #.#.#.#.#.#.#.#.
A whole-file threshold of, say, 7.5 catches the fully replaced file but not the intermittent one, whose whole-file entropy sits between text and random. Per-block entropy catches both, and the alternating pattern is itself a signature of intermittent encryption.
How entropy is used in detection
- Triage of samples: per-section entropy in PE files (above about 7.2 for a code section, or a large high-entropy overlay) flags packing (PE triage); YARA's
math.entropy()does the same in a rule (YARA modules). - Ransomware detection: EDR and file-server monitors combine the entropy of written data, the rate of rewrites and renames, and the file type expected for the extension (Malware and Ransomware).
- Forensics: unexplained high-entropy files or containers (an encrypted volume, an archive of stolen data staged for exfiltration).
How to avoid misreading it
- Always state the window size with an entropy value, and compare like with like.
- Check the file type first: ZIP-based Office files, JPEG, MP4 and PDF streams are compressed by design.
- Combine entropy with chi-square, with the structure of the file (does the header still parse?) and with behaviour.
Pitfalls
- One number per file: hides partial encryption and small encrypted configurations inside large files.
- Tiny windows: random data scores 7.2 at 256 bytes, so a 7.5 threshold misses it.
- Encoding hides entropy: Base64 of random data has at most 6 bits per byte, hex at most 4. A Base64 blob near 6 is a lead (decoding).
- Packers that lower entropy on purpose exist (padding with zeros or text). Low entropy is not proof of "not packed".
Practice
1. What entropy does a Base64 encoding of perfectly random data approach, and why?
At most 6 bits per byte, because Base64 uses only 64 symbols (). Over a long input of random bytes it approaches 6.
2. A 20 MB file has whole-file entropy 6.1. Can it still be the output of ransomware?
Yes. With intermittent encryption only some blocks are encrypted; the per-block profile would show alternating blocks near 8. Check blocks, the header and whether the file still opens.
3. In the first example, roughly how many standard deviations above the uniform mean is the zlib chi-square value?
standard deviations, far outside anything uniform random bytes produce, while the random data () lies about 1.2 standard deviations below the mean, well within the normal range.
Test yourself
Why can't entropy alone separate compressed from encrypted data?
- Entropy is undefined for binary data
- Both have nearly uniform byte histograms, so entropy is close to 8 for both
- Encrypted data has low entropy
- Compressed data has entropy 0
For uniformly random bytes, what is the expected value of the chi-square statistic against the uniform distribution?
- 0
- About 255 (the degrees of freedom)
- About 8
- About 65,536
With a 256-byte window, what entropy does random data typically show?
- Exactly 8.0
- About 7.2
- About 4
- About 6.0
What does an alternating pattern of high- and normal-entropy blocks in a document suggest?
- A text file
- Intermittent (partial) encryption
- A corrupted header only
- A fuzzy hash collision