Live site: https://sebby1770.github.io/image-encryption-system/
A Flask image vault that encrypts photos with AES-256-GCM before they touch disk. Per-image data keys are wrapped with Scrypt+AES or RSA-OAEP, and every new envelope is key-committing (version 4), so one ciphertext can only ever open as one image.
End-to-end mode (the default) encrypts in your browser: metadata is stripped, the image sealed, shared, linked, and decrypted in the page, and the server only ever stores ciphertext and key wraps it cannot open. Server mode is still there for TIFF and for clients without JavaScript.
Cloaked exports hide an encrypted image inside an ordinary-looking picture, and the Cipher Lab puts chaotic, wavelet, Fourier and neural image ciphers next to the vault's AES-256-GCM, scores them with the statistics papers report, and breaks the weak ones with real attacks.
-
Key-committing envelopes (version 4). AES-GCM alone lets one ciphertext carry a valid tag under two different keys, so an owner could give two share recipients two keys that open the same stored image as two different pictures. Version 4 derives the GCM key and a 32-byte commitment from the data key with HKDF-SHA256 and refuses any other key before decrypting, in Python, the CLI and the browser alike. A test builds that two-key forgery for real: version 3 opens it under both keys, version 4 under one. Re-keying upgrades an older image.
-
Cloaked exports. Download any vault image hidden in a PNG that looks like a landscape (generated, four styles) or a photo of your own: the encrypted
.iesfile goes into the low bits of the picture's integer-wavelet detail coefficients, about 45 dB PSNR at 2 bits. It needs only ciphertext, so it works for end-to-end images;ies uncloakories decrypton the PNG gets it back, and any recompression is reported, never a wrong file. -
Cipher Lab (
/labandies lab). Eleven lossless image ciphers: Arnold cat map, logistic-map XOR, a hyperchaotic Chen cipher, integer-wavelet scrambling, a Walsh-Hadamard mask, Fourier double random phase encoding, a keyed integer neural network, AES-ECB, AES-CTR with a reused IV, and the vault's AES-GCM as version 3 and 4. Each is scored (entropy, local entropy, chi-square, correlation, NPCR/UACI, key sensitivity) and attacked: one chosen image breaks the cat map, logistic XOR and reused-IV CTR, three break the wavelet scrambler, one impulse breaks Walsh-Hadamard and DRPE, ECB and the neural network act as codebooks, and only GCM refuses tampering. See docs/CIPHER_LAB.md. -
End-to-end encryption in the browser. WebCrypto AES-256-GCM, a pure JavaScript Scrypt in a Web Worker, and RSA-OAEP, producing the same
.iesenvelope the server and CLI read. Upload, view, share, capability links, and passphrase rotation all run in the page; the server refuses to unwrap an end-to-end key even when handed the right secret. -
Metadata stripped before encryption, in the browser too: EXIF and GPS, XMP, IPTC, MPF, PNG text and C2PA chunks, JPEG thumbnails, comments, and data appended after the image, with every pixel kept.
-
End-to-end links keep their key in the URL fragment, which browsers never send; the server counts downloads but cannot open what it serves.
-
Re-key an end-to-end image to make revocation stick: it is re-encrypted in the browser under a new key, so a key a former recipient kept no longer opens what the server stores.
-
Batch and drag-and-drop uploads in end-to-end mode, and a dark mode that follows your system setting.
-
Key fingerprints for comparing a recipient's key out of band before trusting a share.
-
Account private keys sealed with Scrypt + AES-GCM, not OpenSSL's 2,048-round PBKDF2, and written
0600. Older PEM keys keep working and are resealed at the next sign-in. -
AES-256-GCM encryption for PNG, JPEG, WEBP, GIF, BMP, and TIFF images, with a fresh 256-bit data key per image.
-
Data keys wrapped with Scrypt + AES-GCM (passphrase mode) or RSA-OAEP-SHA256 (hybrid mode, 3072-bit per-user key pair generated at registration; the private key is sealed with the account password).
-
Share with another username by re-wrapping the same data key with their RSA public key. Recipients decrypt with their password. Revoke at any time, with optional expiry (
expires_hours/expires_days). -
Capability links (
/l/<token>) for people without accounts, with optional expiry and download cap. Only the SHA-256 of the token is stored. -
Rotate the passphrase wrap of an image without rewriting its ciphertext.
-
Change password: new hash, RSA private key re-encrypted,
token_versionbumped so other sessions and JWTs stop working. -
Delete account (
POST /account/delete) with password confirmation. -
Envelopes (version 3, and version 4 on top of key commitment) seal the image's owner, asset id, algorithm, wrap type, MIME type, format, and dimensions into the AES-GCM AAD, so ciphertext cannot be swapped between records or accounts. Version 1 files stay decryptable.
-
Capture metadata is stripped before encryption: EXIF (including GPS), XMP, IPTC, PNG text chunks, and JPEG/GIF comments.
-
Uploads are identified from their header and bounded (format allow-list, 64 MP pixel ceiling across all frames, 8 MB byte limit) before anything decodes them.
-
Decrypted images are served only as the allow-listed type they parse as, with
no-store,nosniff, and a sandboxing CSP. -
Ciphertext SHA-256 recorded at save time and checked before decrypt.
-
CSRF tokens on every HTML POST form; strict CSP (no inline script).
-
Server-side session registry: logout and password changes really end sessions; 30-minute idle and 7-day absolute timeouts.
-
Login rate limit (5 / 10 minutes per IP+username) and lockout after 8 failures, persisted in SQLite.
-
Throttles beyond the login form: registration per address (each one mints an RSA-3072 key pair, so it is a CPU amplifier reachable without an account), decrypt attempts per account, and capability-link requests per address.
-
Password policy enforced in storage, so registration, rotation, and the CLI all clear the same bar; a register-page meter mirrors the same rules.
-
Scrypt at
n=2^16for new passphrase wrappings. The accepted floor (2^14) is a separate constant, so older files stay readable. -
API tokens carry and require an audience, alongside
exp,iat,iss,sub, andver. -
Permissions-Policy, COOP, CORP, and HSTS (on HTTPS requests) alongside the CSP;
GET /healthzfor probes; a non-root Docker image. -
Owner-only audit log, HMAC-chained and verified on every view (web, CSV export, and
GET /api/audit). -
Encrypted backup zip (ciphertext + metadata, never private keys) and restore.
-
Rename, notes, and favorites on vault items.
-
JWT API for listing images, sharing, links, and the audit trail.
-
iesCLI for offline encrypt / decrypt / keygen / inspect / verify / rewrap / hash.
Python 3.10+, Flask, cryptography (OpenSSL), Pillow, SQLite, PyJWT. PyCrypto is intentionally not used because it is unmaintained.
git clone https://github.com/Sebby1770/image-encryption-system.git
cd image-encryption-system
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
python run.pyOpen http://127.0.0.1:5000, create an account, and upload an image.
ies encrypt IN.png --passphrase 'a long secret' --out out.bin
ies decrypt out.bin --passphrase 'a long secret' --out restored.png
ies inspect out.bin
ies verify out.bin --passphrase 'a long secret'
ies hash out.bin
ies rewrap out.bin --old-passphrase 'a long secret' --new-passphrase 'rotated' --out rotated.ies
ies keygen --passphrase 'account password' --out-private key.key --out-public pub.pem
ies encrypt IN.png --public-key pub.pem --out photo.ies
ies decrypt photo.ies --private-key key.key --passphrase 'account password' --out restored.png
ies cloak photo.ies -o photo.png --palette alpine # hide it in a landscape
ies cloak photo.ies -o beach.png --cover beach.jpg --bits 1
ies uncloak photo.png -o photo.ies # or: ies decrypt photo.png ...
ies lab list
ies lab run --sample test-card --size 256 --html lab.html --json lab.json
ies lab run --image mine.jpg --cipher hyperchaos --cipher aes-gcm-v4 --seed demoThe CLI talks only to crypto.py. It does not start Flask or write decrypted
images unless you pass --out. inspect prints algorithm and version only.
verify unwraps the data key and exits 0 or 1. keygen seals the private key
with Scrypt; --pem writes OpenSSL-compatible PKCS#8 instead, which is far
cheaper to brute-force. A .ies downloaded from an end-to-end image opens in
the CLI like any other, and every command that reads an .ies also reads a
cloaked PNG. inspect says whether an envelope is key-committing.
Cloak on any image you own downloads it as an ordinary PNG: a generated landscape (dusk, alpine, desert or ocean, with an optional seed) or your own picture, enlarged if it is too small. The vault file is written into the low 1-3 bits of the picture's integer Haar wavelet detail coefficients, spread evenly by a golden-ratio slot order, behind a whitened header with its length and SHA-256.
| Bits per coefficient | Capacity at 960x640 | PSNR at full capacity |
|---|---|---|
| 1 | 172,756 bytes | 50.6 dB |
| 2 | 345,512 bytes | 45.6 dB |
| 3 | 518,268 bytes | 38.9 dB |
The cloak is not a secret: the AES-256-GCM envelope inside is what protects the
image. It hides from a casual viewer that a picture carries a vault file; it
does not resist steganalysis, and recompressing, resizing or editing the PNG
destroys what it carries (uncloak then says so instead of returning a wrong
file).
/lab (and ies lab run) encrypts one image eleven ways and reports, for each
cipher, a verdict decided by attacks (Broken, Leaks, "Strong, not
key-committing", "Strong + committing"), the evidence images, and the statistics
image-encryption papers use, each with its pass rule. Uploads are processed in
memory and never stored. The main lesson is printed on the page: the
hyperchaotic cipher passes every statistic and is still deterministic and
unauthenticated, so statistics alone never show that a cipher is secure.
docs/CIPHER_LAB.md explains every cipher, metric and
attack, with references.
Choose In this browser (the default once the page's module loads):
- The browser strips capture metadata, encrypts the image with a fresh data key, and wraps that key with your passphrase (Scrypt) or your account public key (RSA-OAEP).
- Only the ciphertext and the envelope are uploaded. The server validates everything it can without the key and stores it.
- Decrypt in browser fetches the ciphertext and opens it in the page. For RSA images and anything shared with you, your account password unlocks your private key in the page, once per visit; it is never sent.
- Share re-wraps the data key to the recipient's public key in your browser and shows their key fingerprint. They can read the same value on their Account page.
- Link creates a URL whose key is after the
#. Anyone with the whole link can decrypt it in their browser, within its expiry and download cap. - Re-key re-encrypts the image under a new key in your browser. Choose which recipients keep access; every other share and every link stops working, and a key anyone saved from before no longer opens the stored ciphertext.
End-to-end mode protects against a server that is curious, compromised later, or leaking its storage. It cannot protect against a server that is malicious while you use it, since that server supplies the JavaScript. See docs/SECURITY_MODEL.md.
On the dashboard, choose Share and enter another username. The server:
- Unwraps the AES data key with your passphrase (AES-GCM mode) or your RSA private key (hybrid mode).
- Re-wraps that same key with the recipient's RSA public key.
- Stores the new wrap in
shares. The ciphertext file is unchanged.
The recipient sees the image under Shared with me and decrypts it with their
account password. A third user cannot unwrap the shared key. The owner can
Revoke a recipient at any time; that deletes the shares row so decrypt
fails for them. Optional expires_hours (or expires_days) stores expires_at;
an expired share is treated as revoked on decrypt. The dashboard shows the
expiry.
AES-GCM passphrase assets also have Rotate passphrase: the server unwraps the data key with the old passphrase and writes a new wrap. Shares stay valid because they hold their own RSA wrap of the same data key.
GET /audit lists your events only: login, upload, decrypt, share, revoke,
rotate, password change, delete, and backup. GET /api/audit returns the same
data as JSON.
GET/POST /account/password verifies the current password, stores a new hash,
increments token_version, and re-encrypts user-<id>-private.pem with the
new password. Other browser sessions and JWTs whose ver claim no longer
matches are rejected. RSA-hybrid decrypt then uses the new password, not the
old one. Image ciphertext is never rewritten.
POST /account/delete confirms the password (and CSRF) then deletes the
account: vault blobs, shares, RSA keys, audit rows, and the user.
GET /backupdownloads a zip of your encrypted blobs plusmanifest.json.POST /restore(dashboard form) imports that zip into the current account. Every entry is validated first, so a bad backup restores nothing. Restoring the same backup twice does not duplicate images. Images in a sealed-context format (versions 3 and 4) can only be restored into the account that exported them; version 1 images can be restored anywhere.- Private keys and password hashes are never included.
- Each vault item can also be downloaded as a portable
.iesfile.
| Variable | Purpose |
|---|---|
SECRET_KEY |
Flask session signing (generated and persisted in the instance dir if unset) |
JWT_SECRET |
JWT HMAC secret (derived from SECRET_KEY if unset) |
AUDIT_HMAC_KEY |
Audit chain key; keep it off the database host (generated if unset) |
IES_SECURE_COOKIES |
1 behind HTTPS to mark the session cookie Secure |
IES_INSTANCE_DIR |
SQLite, vault blobs, and RSA keys |
IES_MAX_UPLOAD_BYTES |
Upload cap (default 8 MiB) |
IES_HSTS_SECONDS |
HSTS max-age, sent only on HTTPS requests (default one year; 0 disables) |
IES_MIN_PASSWORD_LENGTH |
Minimum password length (default 10) |
IES_REGISTER_RATE_LIMIT / _WINDOW |
Registrations per address per window (default 5 / 3600 s) |
IES_DECRYPT_RATE_LIMIT / _WINDOW |
Decrypt attempts per account per window (default 30 / 300 s) |
IES_LINK_RATE_LIMIT / _WINDOW |
Capability-link requests per address per window (default 20 / 300 s) |
IES_LAB_RATE_LIMIT / _WINDOW |
Cipher Lab runs per account per window (default 6 / 600 s) |
IES_CLOAK_RATE_LIMIT / _WINDOW |
Cloaked downloads per account per window (default 10 / 600 s) |
IES_LAB_IMAGE_SIZE |
Side of the square the lab works at (default 256; 32-512, powers of two) |
IES_CLOAK_MAX_PIXELS |
Largest cover the cloak will draw or accept (default 12,000,000; automatic bits step up to 3 to stay under it) |
A throttle limit of 0 disables that throttle.
Use strong secrets for any shared deployment.
Uploaded images are re-encoded without capture metadata when any is present, then encrypted with a random 256-bit data key using AES-GCM. The AAD seals the image's context (owner, asset id, type, and size). The selected algorithm controls how that data key is protected:
AES-GCM passphrase: Scrypt derives a wrapping key, then AES-GCM wraps the data key.RSA hybrid: RSA-OAEP-SHA256 wraps the data key with the user's public key.
Version 4 envelopes never use the data key directly: HKDF-SHA256 derives the image's AES-GCM key and a 32-byte key commitment (over the nonce and the sealed context) from it, and decryption checks the commitment before AES-GCM runs.
The decrypted image is streamed to the authorized user and is not written to disk by the web app.
See docs/SECURITY_MODEL.md for goals, non-goals, trust boundaries, and production hardening notes.
curl -X POST http://127.0.0.1:5000/api/token \
-H 'Content-Type: application/json' \
-d '{"username":"alice","password":"correct horse battery staple"}'List encrypted images (owned + shared):
curl http://127.0.0.1:5000/api/images \
-H 'Authorization: Bearer <token>'Read your audit log:
curl http://127.0.0.1:5000/api/audit \
-H "Authorization: Bearer <token>"python -m pip install -e '.[dev]'
ruff check src tests scripts run.py
ruff format --check src tests scripts run.py
mypy
pytestThe Cipher Lab and cloak tests run in seconds; pytest -m "not slow" skips the
one full-size lab run.
The suite includes Hypothesis property tests (tests/test_properties.py):
flipping any byte of an .ies file must make decryption fail, CLI and web
uploads must round-trip, and out-of-bounds KDF parameters must be rejected
cheaply. There is also a Playwright browser test that registers two users,
uploads, views, shares, revokes, and checks that the recipient is locked out:
pip install -e '.[e2e]' && python -m playwright install chromium
pytest -m e2e tests/e2eThe browser crypto has its own tests. node --test covers the JavaScript
directly (including the RFC 7914 Scrypt vectors), and
tests/test_browser_crypto.py runs the real modules under Node against
crypto.py, hashlib.scrypt, and Pillow: envelopes open in both directions,
AADs match byte for byte on hostile Unicode, and stripped images decode to
identical pixels with no metadata left. A second browser test drives the whole
end-to-end flow and records every request to prove that no plaintext,
passphrase, account password, or link key reaches the server.
node --test tests/js/*.test.mjsCI runs lint, format, mypy, the Node tests, and pytest (85% coverage gate, 200
Hypothesis examples per property) on Python 3.10 through 3.13, the browser
tests in their own job, and a pip-audit dependency scan.
image-encryption-system/
src/image_encryption_system/
crypto.py # AES-GCM, RSA-OAEP, .ies container, key re-wrap, v4 commitment
storage.py # SQLite, shares, audit, backup zip
web.py # Flask app, auth, share, revoke, audit, API
lab_routes.py # /lab and /images/<id>/cloak
cli.py # ies console script
security.py # login guard, request throttles, password policy
iwt.py, quality.py # integer Haar lifting; PSNR and SSIM
covers.py # generated landscape covers
cloak.py # hide an .ies file in a PNG, and get it back
lab/ # Cipher Lab: ciphers, metrics, attacks, runner, report
templates/ # HTML views
static/css/ # UI styling
static/js/ # ies-crypto.js, ies-image.js, scrypt worker, page modules
tests/ # pytest coverage
tests/js/ # node --test suite and the harness Python tests drive
docs/ # Threat model, Cipher Lab guide, design spec and plan
docker compose up --buildThe image builds the wheel in a throwaway stage and runs it with gunicorn as a
non-root user, with a HEALTHCHECK against /healthz. The vault database,
ciphertext, encrypted private keys, and the generated secrets all live in the
vault-data volume mounted at /data. compose.yaml sets IES_SECURE_COOKIES=1
(serve it behind TLS) and a memory limit, because Scrypt holds ~64 MiB per
in-flight passphrase decrypt.
This is a portfolio-ready educational project, not a complete production security product. Review the threat model before storing real sensitive photos.