File Encryptor — Rust source
Encrypt or decrypt any file with AES-256-GCM in your browser. Password-based, zero server contact. Drag, drop, done.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! file-encryptor — password-based file encryption (PBKDF2 + AEAD shape).
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `file-encryptor` tool, ported from
//! src/lib/file-encryptor.ts (the canonical TypeScript implementation).
//!
//! std has no AES-GCM, no PBKDF2, no hash functions, and no CSPRNG, so — like
//! the age-encryption port — this file builds the lib's security shape from
//! primitives it can construct itself: SHA-256 (hand-rolled below),
//! HMAC-SHA256, PBKDF2-HMAC-SHA256 (100k iterations) key stretching, a fresh
//! random salt + IV per encryption, and an encrypt-then-MAC tag over a
//! SHA-256 counter-mode keystream. Randomness comes from `RandomState`'s
//! OS-seeded SipHash (display-snippet grade; real deployments want the
//! `getrandom` crate). The wire layout matches the TS reference's
//! (salt || IV || ciphertext || tag) but the bytes are NOT interchangeable,
//! because the AEAD differs.
//!
//! display source — part of CosmoDev's polyglot tool pages.
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
pub const SALT_LENGTH: usize = 16;
pub const IV_LENGTH: usize = 12;
pub const ITERATIONS: u32 = 100_000;
/// GCM appends a 16-byte auth tag to the ciphertext; the smallest possible
/// encrypted payload is therefore salt + IV + tag = 44 bytes.
const TAG_LENGTH: usize = 16;
pub const MIN_LENGTH: usize = SALT_LENGTH + IV_LENGTH + TAG_LENGTH;
/// Fill `n` bytes with pseudorandom material. std has no CSPRNG, but
/// `RandomState::new()` seeds a fresh SipHash key from OS entropy on every
/// call; hashing a counter through it extends that seed into a byte stream.
fn random_bytes(n: usize) -> Vec<u8> {
let builder = RandomState::new();
let mut out = Vec::with_capacity(n);
for i in 0..n.div_ceil(8) {
let mut h = builder.build_hasher();
h.write_u64(i as u64);
out.extend_from_slice(&h.finish().to_le_bytes());
}
out.truncate(n);
out
}
/// SHA-256 (FIPS 180-4), hand-rolled since std has no hash functions.
fn sha256(data: &[u8]) -> [u8; 32] {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa81a664b, 0xa2bfe8a1,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
// Pad: 0x80, zeros to 56 mod 64, then the 64-bit big-endian bit length.
let mut msg = data.to_vec();
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
for block in msg.chunks(64) {
let mut w = [0u32; 64];
for (i, word) in block.chunks(4).enumerate() {
w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut v = h;
for i in 0..64 {
let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
let t1 = v[7]
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
let t2 = s0.wrapping_add(maj);
v = [t1.wrapping_add(t2), v[0], v[1], v[2], v[3].wrapping_add(t1), v[4], v[5], v[6]];
}
for i in 0..8 {
h[i] = h[i].wrapping_add(v[i]);
}
}
let mut out = [0u8; 32];
for (i, word) in h.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
/// HMAC-SHA256 (RFC 2104): hash the message into the padded key, then hash
/// that into the key again — the standard two-pass construction.
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
let mut k = [0u8; 64];
if key.len() > 64 {
k[..32].copy_from_slice(&sha256(key));
} else {
k[..key.len()].copy_from_slice(key);
}
let mut inner = Vec::with_capacity(64 + msg.len());
let mut outer = vec![0x5cu8; 64];
for i in 0..64 {
inner.push(k[i] ^ 0x36);
outer[i] ^= k[i];
}
inner.extend_from_slice(msg);
outer.extend_from_slice(&sha256(&inner));
sha256(&outer)
}
/// PBKDF2-HMAC-SHA256, single 32-byte output block: XOR the 100k-iteration
/// chain together — the same stretch Web Crypto's PBKDF2 performs in the lib.
fn pbkdf2_sha256(password: &[u8], salt: &[u8]) -> [u8; 32] {
let mut block = salt.to_vec();
block.extend_from_slice(&1u32.to_be_bytes());
let mut u = hmac_sha256(password, &block);
let mut out = u;
for _ in 1..ITERATIONS {
u = hmac_sha256(password, &u);
for i in 0..32 {
out[i] ^= u[i];
}
}
out
}
/// Stretch the password into (16-byte enc key, 16-byte MAC key) — two
/// independent halves so the stream cipher and the MAC never share a key.
fn derive_keys(password: &str, salt: &[u8]) -> ([u8; 16], [u8; 16]) {
let material = pbkdf2_sha256(password.as_bytes(), salt);
let mut enc = [0u8; 16];
let mut mac = [0u8; 16];
enc.copy_from_slice(&material[..16]);
mac.copy_from_slice(&material[16..]);
(enc, mac)
}
/// XOR `data` with a SHA-256 counter-mode keystream: pad block i is
/// SHA-256(enc_key || iv || i) — the stream-cipher half of what AES-GCM does
/// in the TS reference.
fn xor_keystream(enc_key: &[u8], iv: &[u8], data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len());
for (i, chunk) in data.chunks(32).enumerate() {
let input: Vec<u8> = enc_key
.iter()
.chain(iv.iter())
.chain((i as u32).to_be_bytes().iter())
.copied()
.collect();
let pad = sha256(&input);
for (b, k) in chunk.iter().zip(pad.iter()) {
out.push(b ^ k);
}
}
out
}
/// Encrypt-then-MAC tag over salt || IV || ciphertext, truncated to 16 bytes
/// (the role GCM's GHASH tag plays in the TS reference).
fn auth_tag(mac_key: &[u8], salt: &[u8], iv: &[u8], ciphertext: &[u8]) -> [u8; 16] {
let mut covered = salt.to_vec();
covered.extend_from_slice(iv);
covered.extend_from_slice(ciphertext);
let full = hmac_sha256(mac_key, &covered);
let mut tag = [0u8; 16];
tag.copy_from_slice(&full[..16]);
tag
}
/// Encrypt `data` under `password`. Returns salt || IV || ciphertext+tag.
pub fn encryptFile(data: &[u8], password: &str) -> Result<Vec<u8>, String> {
if password.is_empty() {
return Err("Password must not be empty.".to_string());
}
if data.is_empty() {
return Err("Input data is empty - nothing to encrypt.".to_string());
}
let salt = random_bytes(SALT_LENGTH);
let iv = random_bytes(IV_LENGTH);
let (enc_key, mac_key) = derive_keys(password, &salt);
let ciphertext = xor_keystream(&enc_key, &iv, data);
let tag = auth_tag(&mac_key, &salt, &iv, &ciphertext);
let mut out = Vec::with_capacity(MIN_LENGTH + data.len());
out.extend_from_slice(&salt);
out.extend_from_slice(&iv);
out.extend_from_slice(&ciphertext);
out.extend_from_slice(&tag);
Ok(out)
}
/// Decrypt a payload produced by `encryptFile`. Fails when the password is
/// wrong or the payload was corrupted/tampered (tag verification failure).
pub fn decryptFile(data: &[u8], password: &str) -> Result<Vec<u8>, String> {
if password.is_empty() {
return Err("Password must not be empty.".to_string());
}
if data.len() < MIN_LENGTH {
return Err(format!(
"Input is too short to be an encrypted file (needs at least {MIN_LENGTH} bytes: salt + IV + auth tag)."
));
}
let salt = &data[..SALT_LENGTH];
let iv = &data[SALT_LENGTH..SALT_LENGTH + IV_LENGTH];
let body = &data[SALT_LENGTH + IV_LENGTH..];
let (ciphertext, tag) = body.split_at(body.len() - TAG_LENGTH);
let (enc_key, mac_key) = derive_keys(password, salt);
let expected = auth_tag(&mac_key, salt, iv, ciphertext);
if tag != expected {
return Err("Decryption failed: wrong password or corrupted file.".to_string());
}
Ok(xor_keystream(&enc_key, iv, ciphertext))
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →