# Side Channels Power Analysis

> Use when you suspect an embedded crypto implementation leaks its key through power consumption on an authorized assessment or in your own lab. Covers building a repeatable trace capture setup, aligning traces, running a correlation power analysis against a Hamming weight model, judging results with signal to noise checks, and reviewing masking and constant time countermeasures. Also use when a timing test is clean but power traces still show data dependent shapes.

- Skill: `mizazhaider-ceh/side-channels-power-analysis` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/side-channels-power-analysis`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/side-channels-power-analysis/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/side-channels-power-analysis

---


Power analysis works because a chip draws measurably different current
depending on the data it processes. A single trace rarely reveals
anything, but thousands of traces of the same operation with known
inputs let statistics separate the key dependent signal from noise.
This sub-skill covers the practical correlation power analysis (CPA)
workflow: capturing clean traces, aligning them, testing a leakage
model, and deciding whether a peak is real or noise. Scope is devices
you own or are authorized to test, and results are reported as
measured leakage, not as a claimed full key recovery unless every key
byte was actually recovered and verified.

## Quick Workflow

1. Pick one target operation with a known input, such as AES first
   round encryption with a fixed key.
2. Set up the measurement: shunt resistor or current probe on the
   device supply, plus a trigger signal marking the operation start.
3. Capture a small pilot set of traces and check they align and the
   trigger is stable.
4. Capture the full set with random known plaintexts, keeping the
   device conditions constant.
5. Align traces to the trigger and remove obvious outliers.
6. Run CPA per key byte against a Hamming weight model of the S-box
   output.
7. Check each candidate peak against noise: re-run on a split of the
   traces and on shuffled labels.
8. Report recovered bytes with their correlation values, and review
   countermeasures for any confirmed leakage.

## 1. Capturing a repeatable trace set

The two properties that matter are a stable trigger and constant
conditions. A drifting clock, a varying supply voltage, or background
tasks on the target all add noise that extra traces cannot always fix.

```python
#!/usr/bin/env python3
"""Pilot capture - record a small trace set and check trigger stability.

This example uses a generic serial trigger and an oscilloscope
abstraction. Replace the capture calls with the API of the scope
actually on the bench; the checks below stay the same.
"""
import statistics

# trigger_offsets holds the sample index of the trigger edge per trace
trigger_offsets = [1024, 1025, 1023, 1024, 1026, 1024, 1025, 1024]

mean = statistics.mean(trigger_offsets)
spread = max(trigger_offsets) - min(trigger_offsets)
print(f"trigger mean - {mean}, spread - {spread} samples")
if spread > 10:
    print("WARNING - trigger is unstable, fix the trigger source before a full capture")
else:
    print("trigger is stable enough for alignment by trigger index")
```

```bash
# Capture discipline checklist, run before the full set
# - target powered from a bench supply, not a noisy USB hub
# - trigger wired to a GPIO toggled around the crypto operation only
# - scope sample rate at least 10x the target clock where possible
# - plaintexts recorded in the same order as traces, one line per trace
# - device kept at one temperature and one supply voltage throughout
ls traces/ | wc -l
head -3 plaintexts.txt
```

## 2. Aligning traces and removing outliers

Traces that are misaligned by even a few samples dilute the
correlation peak. Align on the trigger edge first, then check for
traces that look nothing like the rest, which usually come from
interrupts or a failed trigger.

```python
#!/usr/bin/env python3
"""Align traces to the trigger and drop outlier traces.

Expects traces.npy (shape - traces x samples) and plaintexts.txt
(one hex plaintext per line, in trace order). Writes the cleaned
arrays for the CPA step.
"""
import numpy as np

traces = np.load("traces.npy")
print(f"loaded {traces.shape[0]} traces of {traces.shape[1]} samples")

# Drop traces whose peak amplitude is far from the median trace
medians = np.median(traces, axis=1)
center = np.median(medians)
mad = np.median(np.abs(medians - center)) or 1.0
keep = np.abs(medians - center) < 10 * mad
print(f"keeping {keep.sum()} of {len(traces)} traces after outlier removal")
np.save("traces-clean.npy", traces[keep])
```

## 3. Running correlation power analysis

CPA tests every key byte guess: for each guess, predict the
intermediate value for every plaintext, model its power with the
Hamming weight, and correlate that prediction with the measured
traces at every sample point. The correct guess produces a clear
correlation peak at the sample where the intermediate is processed.

```python
#!/usr/bin/env python3
"""CPA against the AES first round S-box output, one key byte at a time.

Expects traces-clean.npy and plaintexts.txt in matching order.
Prints the best key guess per byte with its peak correlation.
"""
import numpy as np

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, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
    0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
    0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
    0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
    0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
    0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
    0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
    0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
    0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
    0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
    0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
    0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
    0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
    0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
    0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
    0x54, 0xbb, 0x16,
]

def hamming_weight(value):
    return bin(value).count("1")

traces = np.load("traces-clean.npy")
plaintexts = [bytes.fromhex(line.strip()) for line in open("plaintexts.txt")]
plaintexts = np.array(plaintexts[: len(traces)])
traces = traces - traces.mean(axis=0)

for byte_index in range(16):
    best_guess, best_corr = None, 0.0
    for guess in range(256):
        intermediate = np.array(
            [SBOX[p[byte_index] ^ guess] for p in plaintexts]
        )
        model = np.array([hamming_weight(v) for v in intermediate], dtype=float)
        model = model - model.mean()
        corr = np.abs((traces.T @ model) / (np.linalg.norm(traces, axis=0) * np.linalg.norm(model) + 1e-12))
        peak = float(corr.max())
        if peak > best_corr:
            best_guess, best_corr = guess, peak
    print(f"byte {byte_index} - best guess 0x{best_guess:02x}, peak correlation {best_corr:.4f}")
```

## 4. Deciding whether a peak is real

A peak on the full set is not proof. Split the traces in half and
require the same guess to win on both halves, then shuffle the
plaintext labels and require the peak to collapse. A peak that
survives the split but not the shuffle is signal; a peak that
survives neither is noise.

```bash
# Split-half check: same guess must win on each half independently
python3 - <<'EOF'
import numpy as np
# Reuse the CPA script logic on traces-clean.npy halves by slicing
# the trace file and plaintext list before running the analysis.
# Record both halves' winning guesses per byte in the report.
print("split-half check - run CPA on traces 0..N/2 and N/2..N separately")
print("pass criteria - same winning guess per byte on both halves")
EOF

# Shuffle check: randomize plaintext order, CPA peaks should collapse
# toward the noise floor. If a shuffled run still shows a strong peak,
# the measurement setup itself is leaking (for example a trigger artifact).
echo "shuffle check - see report template in section 3 notes"
```

## Edge cases

- Trigger artifacts: a trigger edge inside the capture window creates
  a sharp peak that CPA can mistake for leakage. Keep the trigger
  outside the analyzed window or mask its samples out.
- Misaligned traces: clock drift across a long capture smears peaks.
  Align per trace on a stable feature, not just on the trigger index.
- Too few traces: a peak under 0.05 correlation on a few hundred
  traces is usually noise. Double the trace count before claiming a
  byte.
- Masked implementations: first order CPA fails against properly
  masked code by design. That is a negative result worth reporting,
  not a reason to keep adding traces indefinitely.
- Interrupts during capture: background tasks inject unrelated power
  shapes. Disable interrupts around the target operation where the
  test setup allows it.
- Supply noise from the host: USB powered targets pick up host noise.
  A bench supply and a short, direct ground return reduce this.
- Wrong leakage model: Hamming weight fits data bus writes, Hamming
  distance fits register updates. If one model fails cleanly, try the
  other before concluding there is no leakage.

## Key references

- Paul Kocher, Joshua Jaffe, and Benjamin Jun, Differential Power
  Analysis, the foundational power analysis paper.
- Stefan Mangard, Elisabeth Oswald, and Thomas Popp, Power Analysis
  Attacks, the standard textbook treatment of CPA and countermeasures.
- The parent side-channels skill for timing and electromagnetic
  leakage concepts.
- Chip vendor application notes on shunt resistor measurement and
  supply decoupling for the target board.

