Skip to content

About

Rust port of AES Crypt

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

aescrypt-rs

Crates.io Docs.rs MSRV License

Fast, safe, streaming Rust implementation of the AES Crypt file format

Note

aescrypt-rs is an independent implementation of the AES Crypt file format. It is not affiliated with or endorsed by Paul E. Jones or the official AES Crypt project.

  • Read: Full compatibility with all versions — v0, v1, v2, and v3
  • Write: Modern v3 only (PBKDF2-HMAC-SHA512, PKCS#7 padding, proper session-key encryption)
  • Detect: read_version() — header-only version check in <1 μs (ideal for batch tools)
  • AES-256-CBC with HMAC-SHA256 (payload + session) authentication — PBKDF2-HMAC-SHA512 key derivation
  • Constant-memory streaming in spans of up to 64 KiB, with one HMAC update and one write each
  • Zero-cost secure memory & cryptographically secure RNG via secure-gate
  • Constant-time security: All HMAC comparisons and padding validation use constant-time operations
  • No unsafe in this crate — enforced via #![forbid(unsafe_code)] (dependencies may use unsafe internally, e.g. crypto backends)
  • Round-trip verified against all 63 official v0–v3 test vectors

Support the Original Author

AES Crypt was created and maintained for over two decades by Paul E. Jones. If you find AES Crypt (or this Rust port) useful, please consider supporting Paul directly:

Version Support Summary

Operation v0 v1 v2 v3
Decrypt Yes Yes Yes Yes
Encrypt – – – Yes
Detect version Yes Yes Yes Yes

Why v3-only on write? Version 3 is the only secure, future-proof variant. Producing legacy formats today would be a security downgrade.

Cryptographic Primitives (v3)

Layer Encryption Integrity / KDF
Password → Master Key – PBKDF2-HMAC-SHA512
Session Key + IV (48 B) AES-256-CBC HMAC-SHA256
File Payload AES-256-CBC HMAC-SHA256

Security Features

  • Constant-time operations: All HMAC verifications and PKCS#7 padding validation use constant-time comparisons to prevent timing attacks
  • Secure memory management: Every key, IV, salt and intermediate buffer this crate creates is wrapped in a secure-gate type with automatic zeroization. Two things sit outside that: the caller-owned password (below), and third-party cipher/hasher internals this crate cannot wrap. aes, hmac and sha2 are built with their zeroize features, so the AES key schedule, the HMAC opad/ipad state and SHA-256 hasher state are wiped when they drop. Stale copies left by moves, and the block batch of aes's software backend (used only without hardware AES), are not. See the crate-level Security Model on docs.rs
  • Caller-owned passwords: passwords are taken as &str borrows — read in place, never copied, never stored — so no secure-gate type appears in a signature you have to name, and this crate's secure-gate version stays an internal detail. Zeroizing the password itself is the caller's job; see Password handling
  • Verify before release: decrypt_verified() checks the HMAC (and v3's padding) before it writes any plaintext, so a tampered file or a wrong password writes nothing; it needs a seekable input. decrypt() reads once and verifies last; see Verify before writing plaintext
  • Streaming architecture: Constant-memory encryption and decryption in spans of up to 64 KiB, with one HMAC update and one write per span and no full-file buffering. Spans start at 1 KiB and grow only as the input does, so small files stay cheap.

Password handling

encrypt(), decrypt(), derive_ackdf_key(), derive_pbkdf2_key(), encryption::derive_setup_key() and Pbkdf2Builder::derive_secure*() all take the password as &str. Nothing on that path copies it — the borrow reaches pbkdf2/sha2 as str::as_bytes() and stops there — so you own the password's lifetime and its zeroization. Keep it in a zeroize-on-drop container and hand the API a scoped borrow:

use aescrypt_rs::{encrypt, aliases::PasswordString, constants::DEFAULT_PBKDF2_ITERATIONS};
use secure_gate::RevealSecret;
use std::io::Cursor;

let secret = PasswordString::new("correct horse battery staple".to_string());
let mut ciphertext = Vec::new();

// caller keeps the secret wrapped; the borrow never escapes
secret.with_secret(|pw| {
    encrypt(Cursor::new(b"top secret"), &mut ciphertext, pw, DEFAULT_PBKDF2_ITERATIONS)
})?;
# Ok::<(), aescrypt_rs::AescryptError>(())

zeroize::Zeroizing<String>, secrecy, or your own wrapper work just as well — anything that derefs to str.

Values derived from the password inside the crate are still wrapped: the UTF-16-LE expansion in derive_ackdf_key() is a secure_gate::Dynamic<Vec<u8>>, and every derived key lands directly in a secure-gate alias.

Dependency coupling

No secure-gate type appears in any signature a consumer must name, so this crate's secure-gate version does not constrain yours. The lower-level primitives under encryption::*, decryption::* and aliases::* are the deliberate exception: naming anything from aliases::* (or calling a function that does) re-acquires the secure-gate version coupling, because two secure-gate versions in one graph produce two distinct types with identical names. Stay on encrypt() / decrypt() / the KDFs and the coupling never appears.

Thread Safety

All public functions are thread-safe (Send + Sync). The library has no shared mutable state, making all operations safe for:

  • Concurrent execution: Call functions from multiple threads simultaneously
  • Async runtimes: Use with tokio::task::spawn_blocking or similar
  • Custom cancellation: Spawn operations in threads and implement your own cancellation via channels or thread handles

Example: Threaded Usage

use aescrypt_rs::{encrypt, aliases::PasswordString, constants::DEFAULT_PBKDF2_ITERATIONS};
use secure_gate::RevealSecret;
use std::io::Cursor;

let secret = PasswordString::new("secret".to_string());
let data = b"large file data...";

// A scoped thread keeps the borrow valid, so the secret stays wrapped in the
// parent frame and still zeroizes on drop.
let result = std::thread::scope(|s| {
    let handle = s.spawn(|| {
        let mut encrypted = Vec::new();
        secret.with_secret(|pw| {
            encrypt(
                Cursor::new(data),
                &mut encrypted,
                pw,
                DEFAULT_PBKDF2_ITERATIONS,
            )
        })
    });
    handle.join().unwrap()
});

result?;
# Ok::<(), aescrypt_rs::AescryptError>(())

For large files, operations may take significant time. Users requiring cancellation should spawn functions in threads and implement their own cancellation mechanism.

Core API

The library provides a minimal, focused API at the root level: High-level functions (99% of use cases):

  • encrypt() - Encrypt data to AES Crypt v3 format
  • decrypt() - Decrypt AES Crypt files (v0-v3)
  • decrypt_verified() - Decrypt from a seekable input, checking the HMAC before writing any plaintext (v0-v3)
  • read_version() - Quick version detection without full decryption

Key derivation:

  • Pbkdf2Builder - Fluent builder for PBKDF2 key derivation
  • derive_ackdf_key() - Low-level ACKDF for v0-v2 files
  • derive_pbkdf2_key() - Low-level PBKDF2 for v3 files

Types and constants:

  • AescryptError - Comprehensive error type
  • Configuration constants via constants::*
  • PasswordString and the other secure-gate aliases via aliases::* — optional; see Dependency coupling

Advanced access: Lower-level functions available via decryption::* and encryption::* module paths for custom flows. These exchange aliases::* types and therefore re-acquire the secure-gate version coupling.

API Examples

Detect file version (header only)

use aescrypt_rs::read_version;
use std::io::Cursor;

// v3 file header
let header = b"AES\x03\x00";
let version = read_version(Cursor::new(header))?;
assert_eq!(version, 3);

// v0 file header (3-byte)
let header = b"AES";
let version = read_version(Cursor::new(header))?;
assert_eq!(version, 0);
# Ok::<(), aescrypt_rs::AescryptError>(())

Standard encrypt / decrypt

use aescrypt_rs::{encrypt, decrypt, constants::DEFAULT_PBKDF2_ITERATIONS};
use std::io::Cursor;

let pw = "correct horse battery staple";
let data = b"top secret";
let mut ciphertext = Vec::new();
encrypt(Cursor::new(data), &mut ciphertext, pw, DEFAULT_PBKDF2_ITERATIONS)?;
let mut plaintext = Vec::new();
decrypt(Cursor::new(&ciphertext), &mut plaintext, pw)?;
assert_eq!(data, &plaintext[..]);
# Ok::<(), aescrypt_rs::AescryptError>(())

For a real password, keep it wrapped and pass a scoped borrow — see Password handling.

Verify before writing plaintext

decrypt() reads its input once, so it writes plaintext before the HMAC at the end of the file is checked; on an error you must discard what it wrote. When the input can seek — a file, a Cursor — use decrypt_verified(). It reads the payload twice: first to check the HMAC (and, for v3, the padding), then to decrypt. A tampered file or a wrong password writes nothing at all. A File is seekable as it is, and the payload is read 64 KiB at a time, so it needs no BufReader.

use aescrypt_rs::{decrypt_verified, encrypt};
use std::io::Cursor;

let pw = "correct horse battery staple";
let mut ciphertext = Vec::new();
encrypt(Cursor::new(b"top secret"), &mut ciphertext, pw, 1)?;

let mut plaintext = Vec::new();
let outcome = decrypt_verified(Cursor::new(&ciphertext), &mut plaintext, pw)?;
assert_eq!(plaintext, b"top secret");
assert_eq!((outcome.version, outcome.plaintext_len), (3, 10));

// Flip one ciphertext byte: verification fails and nothing is written.
let n = ciphertext.len();
ciphertext[n - 33] ^= 1;
let mut out = Vec::new();
assert!(decrypt_verified(Cursor::new(&ciphertext), &mut out, pw).is_err());
assert!(out.is_empty());
# Ok::<(), aescrypt_rs::AescryptError>(())

On any error the caller discards the output. Only two errors come after plaintext has been written: an I/O error during the second pass, and input that changed between the passes. The input must not change during the call.

outcome.length_authenticated() is false for v0–v2. Those formats leave the length of the final block outside the HMAC, so up to 15 bytes at the end can be trimmed or exposed without failing verification. Every byte written is still authentic.

PBKDF2 Key Derivation Builder

For custom key derivation with a fluent API:

use aescrypt_rs::{Pbkdf2Builder, aliases::{Aes256Key32, PasswordString}};
use secure_gate::RevealSecret;

let secret = PasswordString::new("my-secret-password".to_string());

// Use defaults (600,000 iterations, random salt)
let mut key = Aes256Key32::new([0u8; 32]);
secret.with_secret(|pw| Pbkdf2Builder::new().derive_secure(pw, &mut key))?;

// Or customize
let mut custom_key = Aes256Key32::new([0u8; 32]);
secret.with_secret(|pw| {
    Pbkdf2Builder::new()
        .with_iterations(500_000)
        .with_salt([0x42; 16])
        .derive_secure(pw, &mut custom_key)
})?;

// Or get a new key directly
let derived_key = secret.with_secret(|pw| Pbkdf2Builder::new().derive_secure_new(pw))?;
# Ok::<(), aescrypt_rs::AescryptError>(())

Advanced API Access

For custom decryption/encryption flows, access lower-level functions via module paths. Note that these exchange aliases::* (secure-gate) types, which re-introduces the version coupling described under Dependency coupling:

use aescrypt_rs::{
    decryption::{extract_session_data, read_file_version},
    encryption::{derive_setup_key, encrypt_session_block},
    aliases::{Aes256Key32, Iv16},
    constants::DEFAULT_PBKDF2_ITERATIONS,
};
use std::io::Cursor;

let mut reader = Cursor::new(b"encrypted data...");
// Returns (version, reserved) — the second byte is the v1–v3 reserved byte,
// which doubles as the modulo byte on v0–v2.
let (version, _reserved) = read_file_version(&mut reader)?;
let password = "password";

// Read public IV from file header (example placeholder)
let public_iv = Iv16::new([0u8; 16]);
let mut setup_key = Aes256Key32::new([0u8; 32]);
// derive_setup_key(password, &public_iv, DEFAULT_PBKDF2_ITERATIONS, &mut setup_key)?;
let mut session_iv = Iv16::new([0u8; 16]);
let mut session_key = Aes256Key32::new([0u8; 32]);
extract_session_data(&mut reader, version, &public_iv, &setup_key, &mut session_iv, &mut session_key)?;

// Continue custom decryption with StreamConfig::V3, etc.
# Ok::<(), aescrypt_rs::AescryptError>(())

Constants

Configuration constants are available via the constants module:

use aescrypt_rs::constants::{
    DEFAULT_PBKDF2_ITERATIONS, // 600,000 (recommended default)
    PBKDF2_MIN_ITER,           // 1
    PBKDF2_MAX_ITER,           // 5,000,000
    AESCRYPT_LATEST_VERSION,   // 3
};

Performance (release mode, modern laptop)

Workload Throughput
Decrypt 10 MiB ~158 MiB/s
Encrypt 10 MiB (with KDF) ~149 MiB/s
Round-trip 10 MiB ~75 MiB/s

These figures were measured with 300,000 PBKDF2 iterations, the default at the time. The default is now 600,000, which doubles the one-time key-derivation cost per file; throughput after it is unaffected. Note: For very large files (GB+), operations may take minutes. All functions are thread-safe and can be spawned in threads for parallel processing or custom cancellation implementations.

Cargo features

This crate defines no optional features. It always links aes with the zeroize feature, and secure-gate with rand and ct-eq, so secure wiping, CSPRNG-backed encryption, and constant-time comparisons are always in effect.

Command-line tool

aescrypt-cli is a command-line tool built on this crate. It lives in this repository as a separate crate, so the library's dependencies are unaffected.

cargo install aescrypt-cli
aescrypt-cli -e report.pdf        # writes report.pdf.aes
aescrypt-cli -d report.pdf.aes    # writes report.pdf

Passwords come from a terminal prompt, --password-command or --password-file, never from a flag. See its README.

Installation

Requires Rust 1.87+, matching rust-version in this crate’s Cargo.toml (Rust edition 2024). Verify with cargo +1.87 test if you pin an older toolchain.

[dependencies]
aescrypt-rs = "0.2"

Changelog

See CHANGELOG.md for a list of changes.

License

Licensed under MIT or Apache-2.0 at your option.


aescrypt-rs — the modern, safe, and future-proof way to handle AES Crypt files in Rust.

About

Rust port of AES Crypt

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages