cryptainer 2.3.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#![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::{Algorithm, Argon2, Params, Version};
use thiserror::Error;

use rand::{CryptoRng, Rng};

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

#[cfg(feature = "zeroize")]
/// A 32-byte derived key that is zeroized when dropped.
pub type KeyBuffer = Zeroizing<[u8; 32]>;

#[cfg(not(feature = "zeroize"))]
/// A 32-byte derived key.
pub type KeyBuffer = [u8; 32];

/// 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,

    /// The salt did not have the required 16-byte length.
    #[error("invalid salt length: expected 16 bytes, got {actual}")]
    InvalidSaltLength { actual: usize },

    /// The nonce did not have the required 12-byte length.
    #[error("invalid nonce length: expected 12 bytes, got {actual}")]
    InvalidNonceLength { actual: usize },

    /// The ciphertext was shorter than the AES-GCM authentication tag.
    #[error("invalid ciphertext length: expected at least 16 bytes, got {actual}")]
    InvalidCiphertextLength { actual: usize },

    #[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`] or [`encrypt_with_key`].
///
/// The serialized representation is always `salt || nonce || ciphertext`.
/// The salt is 16 bytes, the nonce is 12 bytes, and the ciphertext includes
/// the 16-byte AES-GCM authentication tag.
#[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 {
    /// Parses `salt (16B) || nonce (12B) || ciphertext` bytes.
    ///
    /// The ciphertext must contain at least the AES-GCM authentication tag.
    pub fn from_bytes(data: &[u8]) -> Result<Self, CryptError> {
        if data.len() < 44 {
            return Err(CryptError::InvalidData(
                "encrypted data is too short to contain a salt, nonce, and authentication tag",
            ));
        }

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

    /// Serializes this value as `salt (16B) || nonce (12B) || ciphertext`.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut data =
            Vec::with_capacity(self.salt.len() + self.nonce_bytes.len() + self.ciphertext.len());
        data.extend_from_slice(&self.salt);
        data.extend_from_slice(&self.nonce_bytes);
        data.extend_from_slice(&self.ciphertext);
        data
    }
}

fn argon2_instance() -> Result<Argon2<'static>, CryptError> {
    let params = Params::new(19456, 2, 1, Some(32)).map_err(|_| CryptError::HashingError)?;
    Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
}

/// Derives a 256-bit Argon2id key from `password` and a 16-byte `salt`.
///
/// The parameters are pinned to 19,456 KiB memory, 2 iterations, 1 lane,
/// Argon2id, version 0x13, and a 32-byte output.
pub fn derive_key(password: &str, salt: &[u8]) -> Result<KeyBuffer, CryptError> {
    if salt.len() != 16 {
        return Err(CryptError::InvalidSaltLength { actual: salt.len() });
    }

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

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

    argon2_instance()?
        .hash_password_into(password.as_bytes(), salt, &mut key[..])
        .map_err(|_| CryptError::HashingError)?;

    Ok(key)
}

/// Encrypts `plaintext` with a pre-derived 256-bit `key` and caller-provided
/// 16-byte `salt`.
///
/// The salt is stored in the returned [`CryptData`] for wire-format
/// compatibility, but is not used as input to AES-GCM.
pub fn encrypt_with_key(
    key: &[u8; 32],
    salt: &[u8],
    plaintext: &[u8],
    rng: &mut (impl Rng + CryptoRng),
) -> Result<CryptData, CryptError> {
    if salt.len() != 16 {
        return Err(CryptError::InvalidSaltLength { actual: salt.len() });
    }

    let cipher = Aes256Gcm::new_from_slice(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: salt.to_vec(),
        nonce_bytes,
    })
}

/// Decrypts [`CryptData`] with a pre-derived 256-bit `key`.
pub fn decrypt_with_key(data: &CryptData, key: &[u8; 32]) -> Result<Vec<u8>, CryptError> {
    if data.salt.len() != 16 {
        return Err(CryptError::InvalidSaltLength {
            actual: data.salt.len(),
        });
    }
    if data.nonce_bytes.len() != 12 {
        return Err(CryptError::InvalidNonceLength {
            actual: data.nonce_bytes.len(),
        });
    }
    if data.ciphertext.len() < 16 {
        return Err(CryptError::InvalidCiphertextLength {
            actual: data.ciphertext.len(),
        });
    }

    let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| CryptError::InvalidLength)?;
    let nonce =
        Nonce::try_from(data.nonce_bytes.as_slice()).map_err(|_| CryptError::InvalidLength)?;
    Ok(cipher.decrypt(&nonce, data.ciphertext.as_slice())?)
}

/// Parses and decrypts serialized encrypted data with a pre-derived key.
pub fn decrypt_bytes_with_key(data: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, CryptError> {
    decrypt_with_key(&CryptData::from_bytes(data)?, key)
}

/// 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);
    let key = derive_key(password, &salt)?;
    encrypt_with_key(&key, &salt, plaintext, rng)
}

/// Decrypts data produced by [`encrypt_data`].
pub fn decrypt_data(data: &CryptData, password: &str) -> Result<Vec<u8>, CryptError> {
    let key = derive_key(password, &data.salt)?;
    decrypt_with_key(data, &key)
}

#[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")]
/// Encrypts a serializable value using a pre-derived 256-bit key and bincode.
pub fn encrypt_value_with_key<T: serde::Serialize>(
    value: &T,
    key: &[u8; 32],
    salt: &[u8],
    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_with_key(key, salt, &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)?;
    deserialize_value(bytes)
}

#[cfg(feature = "derive")]
/// Decrypts and deserializes a value with a pre-derived 256-bit key.
pub fn decrypt_value_with_key<T: serde::de::DeserializeOwned>(
    data: &CryptData,
    key: &[u8; 32],
) -> Result<T, CryptError> {
    let bytes = decrypt_with_key(data, key)?;
    deserialize_value(bytes)
}

#[cfg(feature = "derive")]
#[doc(hidden)]
pub fn deserialize_value<T: serde::de::DeserializeOwned>(bytes: Vec<u8>) -> Result<T, CryptError> {
    #[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)
}

#[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.to_bytes())?;
    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(feature = "std")]
/// Reads an encrypted file and decrypts it with a pre-derived 256-bit key.
pub fn decrypt_file_with_key(file_path: &str, key: &[u8; 32]) -> Result<Vec<u8>, CryptError> {
    decrypt_with_key(&load_file(file_path)?, key)
}

#[cfg(all(feature = "std", feature = "derive"))]
/// Loads, decrypts, and deserializes a file with a pre-derived 256-bit key.
pub fn load_value_with_key<T: serde::de::DeserializeOwned>(
    file_path: &str,
    key: &[u8; 32],
) -> Result<T, CryptError> {
    decrypt_value_with_key(&load_file(file_path)?, key)
}

#[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_bytes_round_trip() -> Result<(), CryptError> {
        let mut rng = rand::rng();
        let encrypted = encrypt_data("password", b"serialized secret", &mut rng)?;
        let bytes = encrypted.to_bytes();
        let parsed = CryptData::from_bytes(&bytes)?;

        assert_eq!(parsed.salt, encrypted.salt);
        assert_eq!(parsed.nonce_bytes, encrypted.nonce_bytes);
        assert_eq!(parsed.ciphertext, encrypted.ciphertext);
        assert_eq!(decrypt_data(&parsed, "password")?, b"serialized secret");
        Ok(())
    }

    #[test]
    fn test_derive_and_key_round_trip() -> Result<(), CryptError> {
        let salt = [7u8; 16];
        let key = derive_key("password", &salt)?;
        let mut rng = rand::rng();
        let encrypted = encrypt_with_key(&key, &salt, b"key secret", &mut rng)?;

        assert_eq!(decrypt_with_key(&encrypted, &key)?, b"key secret");
        assert_eq!(
            decrypt_bytes_with_key(&encrypted.to_bytes(), &key)?,
            b"key secret"
        );
        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_derive_key_encrypt_decrypt() -> Result<(), CryptError> {
        let salt = [9u8; 16];
        let key = derive_key("password", &salt)?;
        let mut rng = rand::rng();
        let secret = Secret {
            message: "key secret".into(),
        };
        let encrypted = secret.encrypt_with_key(&key, &salt, &mut rng)?;
        let decrypted = Secret::decrypt_with_key(&encrypted, &key)?;
        let decrypted_from_bytes = Secret::decrypt_bytes_with_key(&encrypted.to_bytes(), &key)?;
        let decrypted_from_password_bytes =
            Secret::decrypt_bytes(&encrypted.to_bytes(), "password")?;

        assert_eq!(decrypted.message, secret.message);
        assert_eq!(decrypted_from_bytes.message, secret.message);
        assert_eq!(decrypted_from_password_bytes.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(())
    }
}