Skip to content

Text Encryptor — Rust source

Encrypt or decrypt text with a password using AES-256-GCM. Share the ciphertext safely - only someone with the password can read it.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! text-encryptor — password-based text encryption (AES-256-GCM + PBKDF2).
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `text-encryptor` tool, ported from
//! src/lib/text-encryptor.ts (the canonical TypeScript implementation).
//!
//! Why this file exists: Rust's std has no crypto primitives, so the
//! WebCrypto surface is substituted with hand-rolled SHA-256 + HMAC + PBKDF2
//! (FIPS 180-4 / RFC 2104 / RFC 8018) and AES-256 + GCM (FIPS-197 / NIST SP
//! 800-38D), all byte-compatible with the TypeScript original. Randomness
//! reads `/dev/urandom` via std::fs, falling back to seeded SHA-256 elsewhere.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// AES S-box (FIPS-197): GF(2^8) inverse with the fixed affine map applied.
const SBOX: [u8; 256] = [
    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,
];

/// SHA-256 round constants (FIPS 180-4, section 4.2.2).
const K64: [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,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

const PBKDF2_ITERATIONS: u32 = 100_000;
const SALT_BYTES: usize = 16;
const IV_BYTES: usize = 12;
const TAG_BYTES: usize = 16;
/// Smallest valid packed payload: salt + IV + one AES-GCM block (tag).
const MIN_BYTES: usize = SALT_BYTES + IV_BYTES + TAG_BYTES;
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// ---------------------------------------------------------------- SHA-256

fn sha256_compress(state: &mut [u32; 8], block: &[u8]) {
    let mut w = [0u32; 64];
    for i in 0..16 {
        w[i] = u32::from_be_bytes([block[4 * i], block[4 * i + 1], block[4 * i + 2], block[4 * i + 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 a, mut b, mut c, mut d) = (state[0], state[1], state[2], state[3]);
    let (mut e, mut f, mut g, mut h) = (state[4], state[5], state[6], state[7]);
    for i in 0..64 {
        let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let ch = (e & f) ^ (!e & g);
        let t1 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(K64[i]).wrapping_add(w[i]);
        let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let maj = (a & b) ^ (a & c) ^ (b & c);
        let t2 = s0.wrapping_add(maj);
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(t1);
        d = c;
        c = b;
        b = a;
        a = t1.wrapping_add(t2);
    }
    for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
        *s = s.wrapping_add(v);
    }
}

fn sha256(data: &[u8]) -> [u8; 32] {
    let mut state = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ];
    let bit_len = (data.len() as u64).wrapping_mul(8);
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&bit_len.to_be_bytes());
    for chunk in msg.chunks_exact(64) {
        sha256_compress(&mut state, chunk);
    }
    let mut out = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// HMAC-SHA256 (RFC 2104): hash((key ^ opad) || hash((key ^ ipad) || data)).
fn hmac_sha256(key: &[u8], data: &[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 + data.len());
    let mut outer = Vec::with_capacity(96);
    for i in 0..64 {
        inner.push(k[i] ^ 0x36);
        outer.push(k[i] ^ 0x5c);
    }
    inner.extend_from_slice(data);
    outer.extend_from_slice(&sha256(&inner));
    sha256(&outer)
}

/// PBKDF2-HMAC-SHA256 (RFC 8018), single 32-byte output block (c = 1 block).
fn pbkdf2_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [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 (o, x) in out.iter_mut().zip(u) {
            *o ^= x;
        }
    }
    out
}

// ---------------------------------------------------------------- AES-256

/// Multiply in GF(2^8) mod x^8 + x^4 + x^3 + x + 1 (b is 1, 2, or 3 here).
fn gmul(mut a: u8, mut b: u8) -> u8 {
    let mut p = 0u8;
    for _ in 0..8 {
        if b & 1 != 0 {
            p ^= a;
        }
        let hi = a & 0x80;
        a <<= 1;
        if hi != 0 {
            a ^= 0x1b;
        }
        b >>= 1;
    }
    p
}

/// AES-256 key schedule: a 32-byte key becomes 15 round keys of 16 bytes.
fn expand_key(key: &[u8; 32]) -> Vec<[u8; 16]> {
    const RCON: [u8; 7] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40];
    let mut w = [[0u8; 4]; 60];
    for i in 0..8 {
        w[i].copy_from_slice(&key[4 * i..4 * i + 4]);
    }
    for i in 8..60 {
        let mut t = w[i - 1];
        if i % 8 == 0 {
            // RotWord + SubWord + round constant
            t = [SBOX[t[1] as usize], SBOX[t[2] as usize], SBOX[t[3] as usize], SBOX[t[0] as usize]];
            t[0] ^= RCON[i / 8 - 1];
        } else if i % 8 == 4 {
            // SubWord only (the extra AES-256 twist)
            t = [SBOX[t[0] as usize], SBOX[t[1] as usize], SBOX[t[2] as usize], SBOX[t[3] as usize]];
        }
        for j in 0..4 {
            w[i][j] = w[i - 8][j] ^ t[j];
        }
    }
    (0..15)
        .map(|r| {
            let mut rk = [0u8; 16];
            for i in 0..4 {
                rk[4 * i..4 * i + 4].copy_from_slice(&w[4 * r + i]);
            }
            rk
        })
        .collect()
}

/// AES-256 forward cipher on one 16-byte block (14 rounds, GCM never needs
/// the inverse cipher — it encrypts in both directions).
fn encrypt_block(rk: &[[u8; 16]], block: &mut [u8; 16]) {
    for (b, k) in block.iter_mut().zip(rk[0]) {
        *b ^= k;
    }
    for rnd in 1..15 {
        for b in block.iter_mut() {
            *b = SBOX[*b as usize]; // SubBytes
        }
        let s = *block;
        for i in 0..16 {
            // ShiftRows: row r of the column-major state rotates left by r.
            let (row, col) = (i % 4, i / 4);
            block[i] = s[((col + row) % 4) * 4 + row];
        }
        if rnd < 14 {
            let s = *block;
            for c in (0..16).step_by(4) {
                // MixColumns via {02}/{03} GF(2^8) polynomials (03*b == 02*b ^ b).
                let t = [s[c], s[c + 1], s[c + 2], s[c + 3]];
                let x = [gmul(t[0], 2), gmul(t[1], 2), gmul(t[2], 2), gmul(t[3], 2)];
                block[c] = x[0] ^ x[1] ^ t[1] ^ t[2] ^ t[3];
                block[c + 1] = t[0] ^ x[1] ^ x[2] ^ t[2] ^ t[3];
                block[c + 2] = t[0] ^ t[1] ^ x[2] ^ x[3] ^ t[3];
                block[c + 3] = x[0] ^ t[0] ^ t[1] ^ t[2] ^ x[3];
            }
        }
        for (b, k) in block.iter_mut().zip(rk[rnd]) {
            *b ^= k;
        }
    }
}

fn encrypt_block_copy(rk: &[[u8; 16]], block: &[u8; 16]) -> [u8; 16] {
    let mut b = *block;
    encrypt_block(rk, &mut b);
    b
}

// -------------------------------------------------------------------- GCM

/// Increment the trailing 32 bits of a CTR block, big-endian mod 2^32.
fn inc32(counter: &mut [u8; 16]) {
    let n = u32::from_be_bytes([counter[12], counter[13], counter[14], counter[15]]).wrapping_add(1);
    counter[12..].copy_from_slice(&n.to_be_bytes());
}

/// Multiply in GF(2^128) (right-shift method, NIST SP 800-38D alg. 1).
fn gmul128(x: u128, y: u128) -> u128 {
    let r: u128 = 0xe1 << 120;
    let (mut z, mut v) = (0u128, y);
    for i in 0..128 {
        if (x >> (127 - i)) & 1 == 1 {
            z ^= v;
        }
        v = if v & 1 == 1 { (v >> 1) ^ r } else { v >> 1 };
    }
    z
}

/// GHASH over whole 16-byte blocks (the caller pads).
fn ghash(h: u128, data: &[u8]) -> u128 {
    let mut y: u128 = 0;
    for chunk in data.chunks_exact(16) {
        y = gmul128(y ^ u128::from_be_bytes(chunk.try_into().expect("16-byte chunk")), h);
    }
    y
}

/// GCTR: XOR `data` with AES(counter) blocks, counting up from `counter0`.
fn gctr(rk: &[[u8; 16]], counter0: [u8; 16], data: &[u8]) -> Vec<u8> {
    let mut counter = counter0;
    let mut out = Vec::with_capacity(data.len());
    for chunk in data.chunks(16) {
        let pad = encrypt_block_copy(rk, &counter);
        let start = out.len();
        out.extend_from_slice(chunk);
        for (i, b) in chunk.iter().enumerate() {
            out[start + i] = b ^ pad[i];
        }
        inc32(&mut counter);
    }
    out
}

/// The GCM pre-counter block J0 for a 96-bit IV: IV || 0x00000001.
fn j0(iv: &[u8; 12]) -> [u8; 16] {
    let mut j = [0u8; 16];
    j[..12].copy_from_slice(iv);
    j[15] = 1;
    j
}

/// GCM tag: AES(J0) XOR GHASH_H(C padded || len(AAD) || len(C) in bits).
/// SP 800-38D feeds GHASH the ciphertext first (zero-padded to a 128-bit
/// boundary), then one 16-byte block holding the bit lengths of the AAD
/// (always 0 here) and of the ciphertext. The length block goes LAST.
fn gcm_tag(rk: &[[u8; 16]], j0_block: &[u8; 16], ciphertext: &[u8]) -> [u8; 16] {
    let h = u128::from_be_bytes(encrypt_block_copy(rk, &[0u8; 16]));
    let mut input = Vec::with_capacity(ciphertext.len() + 16);
    input.extend_from_slice(ciphertext);
    input.extend(std::iter::repeat_n(0u8, (16 - ciphertext.len() % 16) % 16));
    input.extend_from_slice(&0u64.to_be_bytes());
    input.extend_from_slice(&((ciphertext.len() as u64) * 8).to_be_bytes());
    let s = ghash(h, &input);
    let ek_j0 = u128::from_be_bytes(encrypt_block_copy(rk, j0_block));
    (s ^ ek_j0).to_be_bytes()
}

// ------------------------------------------------------------- randomness

/// std has no RNG: read /dev/urandom, falling back to a SHA-256 stretch of
/// (time nanos ^ pid ^ stack address) where that file is unavailable.
fn random_bytes(n: usize) -> Vec<u8> {
    use std::io::Read;
    if let Ok(mut f) = std::fs::File::open("/dev/urandom") {
        let mut buf = vec![0u8; n];
        if f.read_exact(&mut buf).is_ok() {
            return buf;
        }
    }
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let seed = format!("{}|{}|{:p}|{}", nanos, std::process::id(), &nanos as *const _, n);
    let mut buf = sha256(seed.as_bytes()).to_vec();
    while buf.len() < n {
        buf.extend_from_slice(&sha256(&buf));
    }
    buf.truncate(n);
    buf
}

// ----------------------------------------------------------------- Base64

/// bytes -> canonical, padded Base64 (same alphabet and grouping as btoa).
fn bytes_to_base64(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b1 = chunk.first().copied().unwrap_or(0) as u32;
        let b2 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b3 = chunk.get(2).copied().unwrap_or(0) as u32;
        let triple = (b1 << 16) | (b2 << 8) | b3;
        out.push(ALPHABET[((triple >> 18) & 63) as usize] as char);
        out.push(ALPHABET[((triple >> 12) & 63) as usize] as char);
        out.push(if chunk.len() > 1 { ALPHABET[((triple >> 6) & 63) as usize] as char } else { '=' });
        out.push(if chunk.len() > 2 { ALPHABET[(triple & 63) as usize] as char } else { '=' });
    }
    out
}

/// Base64 -> bytes. Accepts surrounding whitespace; errors on any other
/// non-alphabet character, wrong length, or misplaced padding (same
/// error-for-error behavior as the TypeScript codec).
fn base64_to_bytes(b64: &str) -> Result<Vec<u8>, String> {
    let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect();
    if clean.is_empty() {
        return Err("Invalid Base64: input is empty".into());
    }
    if clean.len() % 4 != 0 {
        return Err("Invalid Base64: length must be a multiple of 4".into());
    }
    let bad = clean
        .chars()
        .find(|&c| !(c.is_ascii() && ALPHABET.contains(&(c as u8)) || c == '='));
    if let Some(c) = bad {
        return Err(format!("Invalid Base64: unexpected character \"{c}\""));
    }
    // Shape check ^[A-Za-z0-9+/]+={0,2}$: only up to 2 '=' allowed, at the end.
    let pad = clean.chars().rev().take_while(|&c| c == '=').count();
    if pad > 2 || pad == clean.len() || clean[..clean.len() - pad].chars().any(|c| c == '=') {
        return Err("Invalid Base64: unexpected character \"?\"".into());
    }
    let mut out = Vec::with_capacity(clean.len() / 4 * 3);
    let raw = clean.as_bytes();
    for group in raw.chunks(4) {
        let sextet = |c: u8| ALPHABET.iter().position(|&a| a == c).unwrap_or(0) as u32;
        let triple = (sextet(group[0]) << 18) | (sextet(group[1]) << 12)
            | (sextet(group[2]) << 6) | sextet(group[3]);
        out.push((triple >> 16) as u8);
        if group[2] != b'=' {
            out.push((triple >> 8) as u8);
        }
        if group[3] != b'=' {
            out.push(triple as u8);
        }
    }
    Ok(out)
}

// -------------------------------------------------------------- public API

/// Encrypt UTF-8 `plaintext` under `password` and return the Base64 string
/// packing salt + IV + AES-256-GCM ciphertext (+ tag). Errors if either
/// input is empty. A fresh random salt + IV make every call unique.
pub fn encrypt_text(plaintext: &str, password: &str) -> Result<String, String> {
    if plaintext.is_empty() {
        return Err("Nothing to encrypt: input is empty".into());
    }
    if password.is_empty() {
        return Err("Password must not be empty".into());
    }
    let salt: [u8; SALT_BYTES] = random_bytes(SALT_BYTES).try_into().unwrap();
    let iv: [u8; IV_BYTES] = random_bytes(IV_BYTES).try_into().unwrap();
    let key = pbkdf2_sha256(password.as_bytes(), &salt, PBKDF2_ITERATIONS);
    let rk = expand_key(&key);
    let j0_block = j0(&iv);
    let mut first_counter = j0_block;
    inc32(&mut first_counter);
    let data = gctr(&rk, first_counter, plaintext.as_bytes());
    let tag = gcm_tag(&rk, &j0_block, &data);
    let packed = [salt.to_vec(), iv.to_vec(), data, tag.to_vec()].concat();
    Ok(bytes_to_base64(&packed))
}

/// Decrypt a Base64 string produced by `encrypt_text` back to plaintext.
/// Errors on empty input/password, invalid Base64, a payload too short to be
/// one of ours, or a GCM authentication failure (wrong password / tampered
/// data).
pub fn decrypt_text(ciphertext: &str, password: &str) -> Result<String, String> {
    if ciphertext.trim().is_empty() {
        return Err("Nothing to decrypt: input is empty".into());
    }
    if password.is_empty() {
        return Err("Password must not be empty".into());
    }
    let packed = base64_to_bytes(ciphertext.trim())?;
    if packed.len() < MIN_BYTES {
        return Err("Ciphertext too short - not a valid salt + IV + AES-GCM payload".into());
    }
    let salt = &packed[..SALT_BYTES];
    let iv = &packed[SALT_BYTES..SALT_BYTES + IV_BYTES];
    let body = &packed[SALT_BYTES + IV_BYTES..];
    let (data, tag) = body.split_at(body.len() - TAG_BYTES);
    let key = pbkdf2_sha256(password.as_bytes(), salt, PBKDF2_ITERATIONS);
    let rk = expand_key(&key);
    let j0_block = j0(iv.try_into().unwrap());
    let expected = gcm_tag(&rk, &j0_block, data);
    // Constant-time-style tag comparison: XOR-fold every byte difference.
    if expected.iter().zip(tag).fold(0u8, |acc, (a, b)| acc | (a ^ b)) != 0 {
        return Err("Decryption failed - wrong password or corrupted ciphertext".into());
    }
    let mut first_counter = j0_block;
    inc32(&mut first_counter);
    let plain = gctr(&rk, first_counter, data);
    Ok(String::from_utf8_lossy(&plain).into_owned())
}

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 →