Metadata-Version: 2.4
Name: shardpix
Version: 4.0.1
Summary: Encrypt a file and hide k-of-n shares of its key in ordinary-looking images.
Author: Pasquale Ruotolo
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/Just-Ipavon/shardpix
Project-URL: Documentation, https://github.com/Just-Ipavon/shardpix/tree/main/docs
Project-URL: Issues, https://github.com/Just-Ipavon/shardpix/issues
Project-URL: Changelog, https://github.com/Just-Ipavon/shardpix/blob/main/CHANGELOG.md
Keywords: steganography,shamir,secret-sharing,encryption,aes-gcm,cli
Classifier: Environment :: Console
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=44
Requires-Dist: jpeglib>=1.0
Requires-Dist: numpy>=1.24
Requires-Dist: pillow>=10.0
Requires-Dist: rich>=13.7
Provides-Extra: heic
Requires-Dist: pillow-heif>=0.18; extra == "heic"
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: scipy>=1.10; extra == "dev"
Requires-Dist: pillow-heif>=0.18; extra == "dev"
Provides-Extra: audit
Requires-Dist: bandit>=1.7; extra == "audit"
Requires-Dist: mutmut>=3.0; extra == "audit"
Requires-Dist: pip-audit>=2.7; extra == "audit"
Provides-Extra: bench
Requires-Dist: matplotlib>=3.7; extra == "bench"
Requires-Dist: scikit-image>=0.22; extra == "bench"
Provides-Extra: ml
Requires-Dist: matplotlib>=3.7; extra == "ml"
Requires-Dist: torch>=2.2; extra == "ml"
Dynamic: license-file

# shardpix

[![CI](https://github.com/Just-Ipavon/shardpix/actions/workflows/ci.yml/badge.svg)](https://github.com/Just-Ipavon/shardpix/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://www.python.org/)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/LICENSE)


**English** · [Italiano](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/README.it.md)

Encrypt a file and split its key among ordinary-looking photos. shardpix
gives you two things: the encrypted file (`.spx`), which you can store
anywhere, and *n* photos, one for each person you trust, each hiding a share
of the key. To open the file you need the `.spx`, any *k* of the photos and
the passphrase; with fewer than *k* photos the key cannot be
rebuilt. The photos look unchanged, and how well they hide the shares is
measured, not assumed: see [Why it matters](#why-it-matters).

> **Learning project: internally reviewed, not independently audited.** The
> cryptography comes from the `cryptography` library; secret sharing, the
> embedding and the steganalysis are implemented here. The code has been
> through static analysis, fuzzing, mutation testing, a manual review against
> OWASP ASVS and a second review of 2.0.0 — see the
> [security review](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/06-security-review.md) — but no independent third
> party has audited it. For secrets you cannot afford to lose,
> use established tools such as [age](https://age-encryption.org).

![shardpix sealing a file behind 3 of 5 photos, opening it with three of them, and analysing one image](https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/demo.svg)

## How it works

**Sealing** a file behind 3 of 5 photos:

```mermaid
flowchart LR
    F["notes.pdf"] --> E["AES-256-GCM"]
    K["random key K"] --> E
    E --> V["notes.pdf.spx<br/>encrypted file"]
    K --> S["Shamir, 3 of 5"]
    S --> P["5 photos, one share each<br/>one per holder"]
```

**Opening** it:

```mermaid
flowchart LR
    V["notes.pdf.spx"] --> U["shardpix unseal"]
    P["any 3 of the 5 photos"] --> U
    W["the passphrase"] --> U
    U --> F["notes.pdf"]
```

- **The vault file** (`.spx`) is ciphertext. It can sit on a shared drive or
  in an e-mail: without the key it is useless. Without it, the photos are
  useless too, so keep a copy.
- **The key** exists only as shares. Any 3 of the 5 rebuild it; 2 say nothing
  about it, not even with unlimited computing power.
- **Each share** is about 160 bytes, whatever the size of the file, hidden in
  a photo among candidate positions only the passphrase can find, with its
  few changes placed where the photo is textured, and encrypted so the
  hidden bits look like noise.
- **The passphrase** is one for the whole vault, and `seal` and `embed`
  require one. `--insecure-no-passphrase` hides without: then anyone running
  shardpix can find the shares, but still needs *k* of them and the `.spx`.

To hide a short message or a file in a single image, with no vault file,
use `embed` and `extract`.

## Install

shardpix needs Python 3.10 or later. Install it with
[pipx](https://pipx.pypa.io), which puts it in its own environment and the
`shardpix` command on your `PATH`, so it works in every terminal and every
folder:

```bash
# 1. pipx, once
sudo apt install pipx            # Debian, Ubuntu, Kali
brew install pipx                # macOS
py -m pip install --user pipx    # Windows
pipx ensurepath                  # Linux, macOS; then open a new terminal
py -m pipx ensurepath            # Windows; then open a new PowerShell

# 2. shardpix, from PyPI
pipx install shardpix
shardpix --version
```

Update to the latest version with `pipx upgrade shardpix`, remove it with
`pipx uninstall shardpix`. HEIC photos need the optional extra:
`pipx install "shardpix[heic]"`. To try the code on `main` before it is
released, install from GitHub instead:
`pipx install git+https://github.com/Just-Ipavon/shardpix.git`.

### Windows and PowerShell

shardpix runs the same in PowerShell (Windows 10 and 11, Python 3.10 or
later; every dependency ships ready-made for Windows). Install pipx with
`py -m pip install --user pipx`, run `py -m pipx ensurepath`, open a new
PowerShell window and continue as above (the first `pipx` command works only
in a new window; until then use `py -m pipx`). If `py` is not found, install
Python first: `winget install Python.Python.3.13`. Two things differ from bash:

- PowerShell does not expand `*.jpg` for other programs; shardpix does it
  itself, so `shardpix seal notes.pdf photos\*.jpg -k 3 -p` works as in bash.
- Never redirect a file with `>` (`shardpix extract out.jpg > file.pdf`):
  Windows PowerShell 5 rewrites the bytes as text and corrupts the file. Use
  `-o file.pdf`, which works everywhere.

### For development

To work on the code, use a virtual environment instead. The `shardpix`
command then exists only while that environment is active: in a new
terminal, run `source .venv/bin/activate` again (`.venv\Scripts\activate` on
Windows).

```bash
git clone https://github.com/Just-Ipavon/shardpix.git
cd shardpix
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
```

## Quick start

```bash
# Seal a file behind 3 of 5 photos (prompts for a passphrase)
shardpix seal minutes.pdf photos/*.png -k 3 -p

# Open it with any three of the images
shardpix unseal sealed/minutes.pdf.spx sealed/beach.png sealed/cat.png sealed/street.png -p -o minutes-opened.pdf

# Hide a short message in one image (typed without echo), and read it back
shardpix embed photo.png -o holiday.png -t - -p
shardpix extract holiday.png -p

# Split a secret into printable shares, any 2 of 3 recover it
# (-t - asks for it without echo; -i - reads it from a pipe)
shardpix split -t - -k 2 -n 3 -d shares/
shardpix combine shares/share-*-1.txt shares/share-*-3.txt

# Look for the statistical fingerprints of LSB embedding
shardpix analyze suspicious.png
```

### Options

| Flag | Meaning |
| --- | --- |
| `-k, --threshold` | Images (or shares) needed to recover |
| `-n, --shares` | Shares to create (`split`) |
| `-d, --directory` | Output directory (`seal`: default `./sealed`; `split`: one file per share) |
| `-p, --passphrase` | Prompt for a passphrase |
| `--passphrase-file` | Read the passphrase from the first line of a file |
| `--insecure-no-passphrase` | Hide without a passphrase (`seal`, `embed`): anyone can read it |
| `-P, --holder-passphrases` | One passphrase per image (`seal`, `unseal`, `verify`): each holder reads only their own share |
| `--holder-passphrase-files` | The same, one file per image in the images' order |
| `--allow-weak-passphrase` | Accept a passphrase estimated below 50 bits (`seal`, `embed`) |
| `-t, --text` / `-i, --input` | What to hide: a text in quotes, or a file (`embed`, `split`) |
| `-o, --output` | Output file |
| `--name` | Vault file name (`seal`) |
| `--filename` | With `seal -`: seal standard input under this name (the secret never touches the disk unencrypted) |
| `-f, --force` | Overwrite existing outputs (inputs are never overwritten) |

Passphrases are never accepted as command line arguments, which would leave
them in the shell history and the process list. `shardpix passphrase`
generates a diceware one (6 words, about 77 bits).

### When something is wrong

`unseal` reports what happened to every image — here one holder cropped their
photo and another sent the wrong one — so even a failed recovery tells you
which holder to call:

```text
  Image                Share    Status        Detail
  sealed/cat.png          #3    used
  sealed/street.png       #5    used
  sealed/beach.png        #2    used
  sealed/rocket.png             no payload    no share: wrong passphrase or edited image
  old/photo.png                 no payload    no share: wrong passphrase or edited image
Recovered minutes.pdf (47.1 KiB) to minutes.pdf
```

## Features

| Command | What it does |
| --- | --- |
| `seal` | Encrypts a file and hides one key share in each cover image |
| `unseal` | Opens a vault from any *k* of its images and reports on every image |
| `embed` / `extract` | Hides or recovers a message or file in a single image |
| `split` / `combine` | Shamir secret sharing with printable, authenticated shares |
| `inspect` | Shows whether an image holds a share, and of which vault |
| `analyze` | Runs classical attacks: chi-square and RS on pixels, chi-square on a JPEG's DCT coefficients |
| `capacity` | Shows how many bytes an image can hold |

Damaged images are identified rather than silently breaking the recovery, and
a forged set of shares can never pass for the real key.

## Phone photos and other covers

**Use the photos your phone takes, as they are.** shardpix reads the first
bytes of each cover and hides the share the way that file is stored:

| Cover | How the share is hidden | Output |
| --- | --- | --- |
| JPEG (phone photos, cameras) | In the JPEG's own coefficients (format 9): never decoded or recompressed, same quality tables, EXIF and marker layout (a progressive JPEG is written back as baseline, with a warning) | `.jpg` |
| PNG, TIFF, BMP, RAW export | In the pixels (format 8) | `.png` |
| iPhone HEIC | With `pip install "shardpix[heic]"`: decoded to pixels; better: set the camera to *Most Compatible* (JPEG) | PNG |

Choose textured photos you took yourself and never shared, and send the
results as files, not as "photos" in a messaging app, which re-compresses
them. Details and step-by-step instructions:
[docs/07-covers-and-formats.md](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/07-covers-and-formats.md).

## Why it matters

Splitting a key with Shamir's scheme and hiding the shares in pictures is not
a new idea, and neither is asking whether several images, taken together,
give away what each one hides: that is *pooled steganalysis* (Ker, 2006).
What, as far as we found, had not been measured is the two together - and
together they put the steganographer in the worst case. Studies of pooled
steganalysis let the steganographer choose how to spread a payload, leaving
some images clean. A threshold scheme forbids it: **every image must carry a
whole share, and whoever finds one share often finds others of the same
vault** - the holders know each other, use the same cloud, send to the same
people. Each image adds evidence, and nothing can be done about it.
Schemes that combine secret sharing and steganography ignore the problem:
they are judged image by image, typically with off-the-shelf tools, and most
hide the shares by LSB embedding.

shardpix shows how bad that constraint is and **implements the defence
against it**: only the key is split, so each image carries a share of about
160 bytes whatever the size of the file, and that share is placed by
adaptive embedding where the photo is textured, so the evidence each image
adds is close to nothing: pooled over fifty images it still gives nothing
the detectors used can measure.
([docs/05 §5.7](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md#57-related-work) compares
shardpix with this work.) The measurements:

- **One image is the wrong test.** With LSB-style embedding (format 3, kept
  as a baseline) a trained detector is wrong 42.6% of the time on a single
  512x512 image - it looks almost safe. Given 50 images of the same vault and
  pooling its scores, it is wrong only 7.4% of the time: the shares give the
  vault away together.
- **Adaptive embedding holds.** Format 4 places each share with
  syndrome-trellis codes where the photo is textured; on the same 10,000
  BOSSbase images the pooled detector stays at chance, about 50%, from 1 to
  50 images.
- **Real covers, not lab covers.** Phone photos are JPEG, so shardpix hides
  the share inside the JPEG coefficients themselves (format 9) and returns a
  JPEG with the same quality settings and metadata - no conversion that
  would betray the image. Measured with DCTR and GFR on BOSSbase and on
  ALASKA2, real camera photos: at quality 90-95, like a phone's, one image
  is at chance (49-50%), where the non-adaptive baseline is caught on one
  image (16-39% error) and certainly with ten; over fifty images of one
  vault DCTR shows at most a weak trend at quality 95 (43.6%, an interval
  that still includes 50%). The deep network SRNet, measured on 10,000
  ALASKA2 photos (4,500 training pairs), finds nothing more: at quality 95 it is at chance on one
  image and on fifty (49.8% and 49.2%). At quality 75, typical of photos
  recompressed by chat apps, format 5 falls to 7-16% with fifty, the same
  trap as format 3
  ([docs/05 §5.5.8](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md#558-jpeg-covers-format-5),
  [§5.5.9](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md#559-a-deep-detector-srnet)).
  Use original camera files.
- **Everything is reproducible.** The detectors, the datasets, the positive
  controls and the confidence intervals are in the repository; every number
  in this README can be regenerated.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/pooled-512-dark.png">
  <img alt="Detection error against the number of images of one vault the adversary holds: format 3 falls from 43% to 7% at 50 images, format 4 stays at 50%" src="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/pooled-512-light.png">
</picture>

*Where the numbers come from:* BOSSbase 1.01, 10,000 photographs at
512x512 greyscale, one vault share per image. A detector (SRM-lite features
with an ensemble classifier) is trained on 5,000 images and scores the other
5,000; groups of 1 to 50 images are then pooled by a likelihood ratio, over
40 random calibration/evaluation splits. 42.6% and 7.4% are the medians,
7.4% with a 4.5-11.5% range. Method and full table:
[docs/05 §5.5.7](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md#557-several-images-of-one-vault-pooled-steganalysis);
raw data: [docs/data/pooled_512.json](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/data/pooled_512.json);
reproduce with `python -m shardpix.analysis.pooled`.

## Detectability

The measurements below were made on formats 4 and 5. Formats 6 and 7,
written since a second security review
([docs/06 §6.13](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/06-security-review.md#613-second-review-200)), embed the same way
without the public cost byte, which was a fingerprint anyone with the
source code could read without the passphrase; the measured detection
errors apply to them.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/rs-estimate-dark.png">
  <img alt="RS steganalysis estimate against true embedding rate: LSB replacement is measured almost exactly, shardpix stays near zero at every rate" src="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/rs-estimate-light.png">
</picture>

RS analysis measures classic LSB replacement almost exactly and does not see
shardpix at any rate. At the rate a vault actually uses — 0.05% to 0.5% of the
samples — the median change in the RS estimate over ten photographs is 0.07
points. The least significant bit plane tells the same story to the naked eye:

![Least significant bit plane: clean photo, a naive tool after embedding 50% sequentially, and shardpix after embedding a vault share](https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/lsb-planes.png)

Trained detectors are stronger. On BOSSbase, 10,000 never-compressed
photographs, a rich-model classifier trained under ideal conditions for the
attacker brings a share in a 512x512 greyscale photo to 42.5% detection
error, against 50% for guessing: weak, but not zero. The signal shrinks with
the square root of the cover size: at the lowest rate measured the
detectors were within 1.5 points of chance.

That was format 3. **Format 4, adaptive embedding, is at chance**: the same
detectors on the same 10,000 images are wrong 49.9% of the time on a share,
and only start to see the embedding at 10% of the samples, where format 3
was caught nine times out of ten. Colour photos of 2 megapixels or more
remain the safer choice.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/ml-format-comparison-512-dark.png">
  <img alt="Detection error against embedding rate for format 3 and format 4: format 4 is at 50% at one share and at 43-46% at 10%, where format 3 is at 12-19%" src="https://raw.githubusercontent.com/Just-Ipavon/shardpix/v4.0.1/assets/ml-format-comparison-512-light.png">
</picture>

The full results, the chi-square attack, the trained detectors and the known
limitations are in [docs/05-security-analysis.md](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md).
Reproduce them with `pip install -e ".[bench]"` and
`python -m shardpix.analysis.benchmark`, and for the trained detectors
`pip install -e ".[bench,ml]"` and `python -m shardpix.analysis.ml_benchmark`
on a copy of BOSSbase.

## Design notes

**Split the key, not the file.** Only the 32-byte key is shared, so every
image carries about 160 bytes however large the file is. A small payload is
what keeps the images hard to tell from the originals.

**Shares check each other without leaking anything.** Plain Shamir silently
returns garbage if one share is damaged. Each share here carries a MAC, but the
MAC key is shared together with the secret: fewer than *k* shares stay
independent of the secret even if it is a short password, which would not be
true with a MAC keyed by the secret itself.

**A forged set of shares cannot win.** The vault's group id is public, so
anyone can fabricate shares that authenticate each other. Recovery looks for
every cluster of mutually consistent shares and lets the vault's AES-GCM tag
decide which one is real.

**Measured, then fixed.** The first version used plain LSB matching. The
benchmark showed RS reading 22% on a photo with large black areas: a sample at
0 can only move up, and a one-way move looks exactly like LSB replacement.
Samples outside 2–253 are now never used, and the reading dropped to 4.5%.

**Changes go where the photo is already noisy.** Since format 4 the
payload is written as a syndrome-trellis code over keyed candidate samples:
the encoder may pick which samples to change and picks those with the lowest
HiLL cost, in foliage and grain rather than in the sky. A share changes
about a third as many samples as before (208 against 633 in a 512x512
photo), and the extractor never needs to know where they are.

**Positions cost what the payload costs.** Positions come from a
rejection-sampled ChaCha20 walk keyed by the passphrase and a per-image salt.
Placing a share in a 48-megapixel photo takes as long as in a thumbnail, and
two images sealed with the same passphrase share nothing.

**Every format is pinned.** Known-answer tests fix the walk, the share bytes,
the stego pixels and the vault bytes, so a refactor or a library upgrade that
would make existing images unreadable fails the build first.

## Architecture

```text
shardpix/
├── cli.py              commands, passphrase input, overwrite protection, exit codes
├── vault.py            seal and unseal: AES-256-GCM + Shamir + steganography
├── media.py            JPEG or pixels: picks the format from the file
├── jpeg.py             formats 7 and 5: embedding in JPEG coefficients
├── stego.py            key derivation, keyed walk, formats 6 and 4 (adaptive) and 3, framing
├── stc.py              syndrome-trellis codes (Viterbi)
├── costs.py            HiLL and UERD embedding costs
├── shamir.py           secret sharing, share format, MACs, robust recovery
├── gf256.py            GF(2^8) arithmetic and Lagrange interpolation
├── images.py           any image in, lossless PNG out
├── errors.py           exception hierarchy
├── progress.py         progress callbacks behind the progress bar
└── analysis/
    ├── chi_square.py   Westfeld–Pfitzmann chi-square attack
    ├── rs.py           Fridrich–Goljan–Du RS analysis
    ├── benchmark.py    detectability experiments and charts
    ├── features.py     SPAM, SRM-lite, DCTR and GFR steganalysis features
    ├── ensemble.py     Kodovský–Fridrich–Holub ensemble classifier
    ├── cnn.py          convolutional steganalysis network (PyTorch)
    ├── ml_benchmark.py trained-detector experiments on BOSSbase
    ├── jpeg_benchmark.py the same for JPEG covers (format 5)
    └── pooled.py       an adversary holding several images of one vault
```

`scripts/srnet_colab.py` trains and tests SRNet on a Colab GPU
(docs/05 §5.5.9); it is not part of the package.

## Documentation

Full technical documentation lives in [docs/](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/README.md): architecture
and design decisions, use case specifications, a function-by-function
reference, the runtime behaviour, a security analysis and an internal
security review — with UML diagrams throughout. To report a vulnerability,
see [SECURITY.md](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/SECURITY.md).

| Document | Contents |
| --- | --- |
| [01 — Architecture](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/01-architecture.md) | Context, packages, data model, on-disk formats, thirteen architectural decisions |
| [02 — Use cases](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/02-use-cases.md) | Actors, use case diagram, nine detailed specifications, operational scenarios |
| [03 — Function reference](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/03-function-reference.md) | Every function: behaviour, edge cases, errors, covering tests |
| [04 — Runtime behaviour](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/04-runtime-behaviour.md) | Sequence diagrams, the share recovery algorithm, exit codes, timing |
| [05 — Security analysis](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/05-security-analysis.md) | Threat model, security properties, steganalysis results, limitations |
| [06 — Security review](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/06-security-review.md) | Static analysis, fuzzing, mutation testing, ASVS checklist, findings and fixes |
| [07 — Covers and formats](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/docs/07-covers-and-formats.md) | PNG and JPEG, embedding methods, phone photos |

## License

GNU General Public License v3.0 or later (GPL-3.0-or-later) — see
[LICENSE](https://github.com/Just-Ipavon/shardpix/blob/v4.0.1/LICENSE).
