cryptainer 2.2.0

tiny encrypted byte array container (Argon2id + AES256-GCM)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#![cfg_attr(not(feature = "std"), no_std)]

//! # cryptainer
//!
//! Small, password-based authenticated encryption for Rust.
//!
//! `cryptainer` derives a 256-bit key from a password with Argon2id and
//! encrypts data with AES-256-GCM. It supports `no_std` with `alloc`, while
//! file I/O and typed struct encryption remain opt-in features.
//!
//! ## Feature flags
//!
//! - `std` (default) enables file helpers and standard-library integration.
//! - `derive` enables bincode-backed Serde struct encryption and the
//!   [`Cryptainer`] derive macro.
//! - `zeroize` (default) enables zeroization of derived keys and temporary
//!   serialized plaintext buffers where supported.
//!
//! # Examples
//!
//! ## Encrypt bytes
//!
//! ```
//! # #[cfg(feature = "std")]
//! # fn example() -> Result<(), cryptainer::CryptError> {
//! # use cryptainer::encrypt_data;
//!
//! let mut rng = rand::rng();
//! let data = encrypt_data("password", b"hello world", &mut rng)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Encrypt a struct
//!
//! With the `derive` feature enabled, derive [`Cryptainer`] alongside Serde's
//! `Serialize` and `Deserialize`:
//!
//! ```ignore
//! use cryptainer::Cryptainer;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize, Cryptainer)]
//! struct Secret {
//!     message: String,
//! }
//!
//! let mut rng = rand::rng();
//! let secret = Secret { message: "hello".into() };
//! let encrypted = secret.encrypt("password", &mut rng)?;
//! let decrypted = Secret::decrypt(&encrypted, "password")?;
//! # Ok::<(), cryptainer::CryptError>(())
//! ```
//!
//! ## Security notes
//!
//! Every encryption generates a fresh salt and nonce. The serialized format is
//! `salt (16 bytes) || nonce (12 bytes) || ciphertext`, where the ciphertext
//! includes the AES-GCM authentication tag. Password strength and password
//! transport are the responsibility of the calling application.
//!
//! When `zeroize` is enabled, derived keys and temporary serialized plaintext
//! buffers are cleared when dropped. Returned plaintext and caller-owned
//! buffers remain the caller's responsibility.
//!
//! ## Decrypt bytes
//!
//! ```
//! # #[cfg(feature = "std")]
//! # fn example() -> Result<(), cryptainer::CryptError> {
//! # use cryptainer::{decrypt_data, encrypt_data};
//!
//! let mut rng = rand::rng();
//! let encrypted = encrypt_data("password", b"hello world", &mut rng)?;
//! let plaintext = decrypt_data(&encrypted, "password")?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Save and load files
//!
//! ```
//! # #[cfg(feature = "std")]
//! # fn example() -> Result<(), cryptainer::CryptError> {
//! # use cryptainer::{decrypt_file, encrypt_data, save_file};
//!
//! let mut rng = rand::rng();
//! let data = encrypt_data("password", b"secret", &mut rng)?;
//! save_file("secret.stuff", &data)?;
//!
//! let plaintext = decrypt_file("secret.stuff", "password")?;
//! # Ok(())
//! # }
//! ```
//!
//! With the `derive` feature, load and decrypt a persisted struct directly:
//!
//! ```ignore
//! use cryptainer::{load_value, save_file};
//!
//! save_file("secret.stuff", &encrypted)?;
//! let secret: Secret = load_value("secret.stuff", "password")?;
//! ```

#[cfg(feature = "derive")]
extern crate self as cryptainer;

extern crate alloc;

use alloc::vec;
use alloc::vec::Vec;

#[cfg(feature = "derive")]
pub use cryptainer_derive::Cryptainer;

#[cfg(feature = "std")]
use std::{
    fs::File,
    io::{Read, Write},
};

use aes_gcm::{
    Aes256Gcm, Nonce,
    aead::{Aead, KeyInit},
};

use argon2::Argon2;
use thiserror::Error;

use rand::{CryptoRng, Rng};

#[cfg(feature = "zeroize")]
use zeroize::Zeroizing;

/// Errors returned by encryption, decryption, and file helpers.
#[derive(Error, Debug)]
pub enum CryptError {
    /// Password hashing failed while deriving the encryption key.
    #[error("failed to hash password")]
    HashingError,

    /// AES-GCM failed during encryption or decryption.
    #[error("encryption error: {0}")]
    EncryptionError(#[from] aes_gcm::Error),

    /// A key or nonce did not have the expected length.
    #[error("invalid key or nonce length")]
    InvalidLength,

    #[cfg(feature = "std")]
    /// File I/O failed while reading or writing encrypted data.
    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    /// The input buffer was not large enough or was otherwise malformed.
    #[error("invalid data format: {0}")]
    InvalidData(&'static str),

    /// Serialization or deserialization failed.
    #[cfg(feature = "derive")]
    #[error("serialization error")]
    SerializationError,
}

#[cfg(feature = "derive")]
#[doc(hidden)]
pub mod __private {
    pub use bincode;
    pub use rand;
    pub use serde;
}

/// Encrypted data returned by [`encrypt_data`].
#[derive(Debug)]
pub struct CryptData {
    /// AES-GCM ciphertext including the authentication tag.
    pub ciphertext: Vec<u8>,
    /// Random 16-byte Argon2 salt used to derive the key.
    pub salt: Vec<u8>,
    /// Random 12-byte AES-GCM nonce.
    pub nonce_bytes: Vec<u8>,
}

impl CryptData {
    fn from_bytes(data: &[u8]) -> Result<Self, CryptError> {
        if data.len() < 44 {
            return Err(CryptError::InvalidData(
                "File is too short to contain valid encrypted data",
            ));
        }

        Ok(Self {
            salt: data[0..16].to_vec(),
            nonce_bytes: data[16..28].to_vec(),
            ciphertext: data[28..].to_vec(),
        })
    }
}

/// Encrypts `plaintext` with a key derived from `password`.
///
/// The returned value contains the salt and nonce needed to decrypt the data
/// later. The caller supplies the RNG so applications can control entropy
/// sourcing.
pub fn encrypt_data(
    password: &str,
    plaintext: &[u8],
    rng: &mut (impl Rng + CryptoRng),
) -> Result<CryptData, CryptError> {
    let mut salt = vec![0u8; 16];
    rng.fill_bytes(&mut salt);

    #[cfg(feature = "zeroize")]
    let mut derived_key = Zeroizing::new(vec![0u8; 32]);

    #[cfg(not(feature = "zeroize"))]
    let mut derived_key = vec![0u8; 32];

    Argon2::default()
        .hash_password_into(password.as_bytes(), &salt, derived_key.as_mut_slice())
        .map_err(|_| CryptError::HashingError)?;

    let cipher = Aes256Gcm::new_from_slice(&derived_key).map_err(|_| CryptError::InvalidLength)?;

    let mut nonce_bytes = vec![0u8; 12];
    rng.fill_bytes(&mut nonce_bytes);
    let nonce = Nonce::try_from(nonce_bytes.as_slice()).map_err(|_| CryptError::InvalidLength)?;

    let ciphertext = cipher.encrypt(&nonce, plaintext)?;

    Ok(CryptData {
        ciphertext,
        salt,
        nonce_bytes,
    })
}

/// Decrypts data produced by [`encrypt_data`].
pub fn decrypt_data(data: &CryptData, password: &str) -> Result<Vec<u8>, CryptError> {
    decrypt_parts(&data.salt, &data.nonce_bytes, &data.ciphertext, password)
}

#[cfg(feature = "derive")]
/// Encrypts a serializable value using bincode.
pub fn encrypt_value<T: serde::Serialize>(
    value: &T,
    password: &str,
    rng: &mut (impl Rng + CryptoRng),
) -> Result<CryptData, CryptError> {
    let bytes = bincode::serde::encode_to_vec(value, bincode::config::standard())
        .map_err(|_| CryptError::SerializationError)?;
    #[cfg(feature = "zeroize")]
    let bytes = Zeroizing::new(bytes);

    encrypt_data(password, &bytes, rng)
}

#[cfg(feature = "derive")]
/// Decrypts a bincode-serialized value.
pub fn decrypt_value<T: serde::de::DeserializeOwned>(
    data: &CryptData,
    password: &str,
) -> Result<T, CryptError> {
    let bytes = decrypt_data(data, password)?;
    #[cfg(feature = "zeroize")]
    let bytes = Zeroizing::new(bytes);

    bincode::serde::decode_from_slice(&bytes, bincode::config::standard())
        .map(|(value, _)| value)
        .map_err(|_| CryptError::SerializationError)
}

/// Decrypts serialized data encoded as `salt || nonce || ciphertext`.
pub fn decrypt_bytes(data: &[u8], password: &str) -> Result<Vec<u8>, CryptError> {
    decrypt_data(&CryptData::from_bytes(data)?, password)
}

fn decrypt_parts(
    salt: &[u8],
    nonce_bytes: &[u8],
    ciphertext: &[u8],
    password: &str,
) -> Result<Vec<u8>, CryptError> {
    if salt.len() != 16 || nonce_bytes.len() != 12 || ciphertext.len() < 16 {
        return Err(CryptError::InvalidData("Invalid encrypted data"));
    }

    #[cfg(feature = "zeroize")]
    let mut derived_key = Zeroizing::new(vec![0u8; 32]);

    #[cfg(not(feature = "zeroize"))]
    let mut derived_key = vec![0u8; 32];

    Argon2::default()
        .hash_password_into(password.as_bytes(), salt, derived_key.as_mut_slice())
        .map_err(|_| CryptError::HashingError)?;

    let cipher = Aes256Gcm::new_from_slice(&derived_key).map_err(|_| CryptError::InvalidLength)?;

    let nonce = Nonce::try_from(nonce_bytes).map_err(|_| CryptError::InvalidLength)?;

    let plaintext = cipher.decrypt(&nonce, ciphertext)?;

    Ok(plaintext)
}

#[cfg(feature = "std")]
/// Writes encrypted data to disk in `salt || nonce || ciphertext` order.
pub fn save_file(file_path: &str, data: &CryptData) -> Result<(), CryptError> {
    let mut file = File::create(file_path)?;

    file.write_all(&data.salt)?;
    file.write_all(&data.nonce_bytes)?;

    file.write_all(&data.ciphertext)?;

    Ok(())
}

#[cfg(feature = "std")]
/// Loads serialized encrypted data from disk.
pub fn load_file(file_path: &str) -> Result<CryptData, CryptError> {
    let mut file = File::open(file_path)?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;

    CryptData::from_bytes(&buffer)
}

#[cfg(all(feature = "std", feature = "derive"))]
/// Loads, decrypts, and deserializes a value from disk.
pub fn load_value<T: serde::de::DeserializeOwned>(
    file_path: &str,
    password: &str,
) -> Result<T, CryptError> {
    let data = load_file(file_path)?;
    decrypt_value(&data, password)
}

#[cfg(feature = "std")]
/// Reads an encrypted file from disk and decrypts it with `password`.
pub fn decrypt_file(file_path: &str, password: &str) -> Result<Vec<u8>, CryptError> {
    decrypt_data(&load_file(file_path)?, password)
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[cfg(feature = "derive")]
    use serde::{Deserialize, Serialize};

    #[cfg(feature = "derive")]
    #[derive(Serialize, Deserialize, Cryptainer)]
    struct Secret {
        message: String,
    }

    fn t_encrypt_file() -> Result<(), CryptError> {
        let mut rng = rand::rng();
        let data = encrypt_data("password", "super secret stuff".as_bytes(), &mut rng)?;

        let _ = save_file("secret.stuff", &data)?;

        Ok(())
    }

    fn t_decrypt_file() -> Result<(), CryptError> {
        let data =
            alloc::string::String::from_utf8(decrypt_file("secret.stuff", "password")?).unwrap();

        assert_eq!(data, "super secret stuff");

        Ok(())
    }

    #[test]
    fn test_load_file() -> Result<(), CryptError> {
        let mut rng = rand::rng();
        let encrypted = encrypt_data("password", b"loaded secret", &mut rng)?;
        save_file("secret.stuff", &encrypted)?;

        let loaded = load_file("secret.stuff")?;
        assert_eq!(decrypt_data(&loaded, "password")?, b"loaded secret");

        let _ = std::fs::remove_file("secret.stuff");
        Ok(())
    }

    #[test]
    fn test_encrypt_decrypt() -> Result<(), CryptError> {
        t_encrypt_file()?;
        t_decrypt_file()?;

        let _ = std::fs::remove_file("secret.stuff");

        Ok(())
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_derive_encrypt_decrypt() -> Result<(), CryptError> {
        let mut rng = rand::rng();
        let secret = Secret {
            message: "super secret".into(),
        };
        let encrypted = secret.encrypt("password", &mut rng)?;
        let decrypted = Secret::decrypt(&encrypted, "password")?;

        assert_eq!(decrypted.message, secret.message);
        Ok(())
    }

    #[cfg(feature = "derive")]
    #[test]
    fn test_load_value() -> Result<(), CryptError> {
        let mut rng = rand::rng();
        let secret = Secret {
            message: "loaded secret".into(),
        };
        let encrypted = secret.encrypt("password", &mut rng)?;
        save_file("secret.stuff", &encrypted)?;

        let loaded: Secret = load_value("secret.stuff", "password")?;
        assert_eq!(loaded.message, secret.message);

        let _ = std::fs::remove_file("secret.stuff");
        Ok(())
    }
}