use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use hmac::Hmac;
use sha2::Sha256;
use thiserror::Error;
pub const KEY_LENGTH: usize = 32;
pub const IV_LENGTH: usize = 12;
pub const AUTH_TAG_LENGTH: usize = 16;
pub const SALT_LENGTH: usize = 32;
pub const PBKDF2_ITERATIONS_V1: u32 = 100_000;
pub const PBKDF2_ITERATIONS_V2: u32 = 600_000;
pub const ENCRYPTION_VERSION_V1: u8 = 1;
pub const ENCRYPTION_VERSION_V2: u8 = 2;
pub const HEADER_LENGTH: usize = 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
#[derive(Debug, Error)]
pub enum StorageEncryptionError {
#[error("invalid encrypted data: too short ({0} bytes, header is 61 bytes)")]
TooShort(usize),
#[error("unsupported encryption version: {0}")]
UnsupportedVersion(u8),
#[error("invalid base64: {0}")]
InvalidBase64(#[source] base64::DecodeError),
#[error("decryption failed (wrong password or corrupted ciphertext)")]
Decrypt,
}
pub type Salt = [u8; SALT_LENGTH];
#[derive(Clone)]
pub struct Cipher {
aead: Aes256Gcm,
salt: Salt,
}
impl Cipher {
pub fn derive<R: rand::CryptoRng + rand::RngCore>(rng: &mut R, password: &str) -> Self {
let mut salt = [0u8; SALT_LENGTH];
rng.fill_bytes(&mut salt);
Self::derive_with_salt(password, &salt, PBKDF2_ITERATIONS_V2)
}
#[allow(deprecated)]
pub fn derive_with_salt(password: &str, salt: &Salt, iterations: u32) -> Self {
let mut key = [0u8; KEY_LENGTH];
pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), salt, iterations, &mut key)
.expect("PBKDF2 with a 32-byte key length is infallible");
let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));
Self { aead, salt: *salt }
}
pub fn derive_for_version(
password: &str,
salt: &Salt,
version: u8,
) -> Result<Self, StorageEncryptionError> {
let iterations = match version {
ENCRYPTION_VERSION_V1 => PBKDF2_ITERATIONS_V1,
ENCRYPTION_VERSION_V2 => PBKDF2_ITERATIONS_V2,
other => return Err(StorageEncryptionError::UnsupportedVersion(other)),
};
Ok(Self::derive_with_salt(password, salt, iterations))
}
#[must_use]
pub fn salt(&self) -> &Salt {
&self.salt
}
#[allow(deprecated)]
pub fn encrypt<R: rand::CryptoRng + rand::RngCore>(
&self,
rng: &mut R,
plaintext: &str,
) -> String {
let mut iv = [0u8; IV_LENGTH];
rng.fill_bytes(&mut iv);
let ct_with_tag = self
.aead
.encrypt(
Nonce::from_slice(&iv),
Payload {
msg: plaintext.as_bytes(),
aad: &[],
},
)
.expect(
"AES-256-GCM encryption with a 32-byte key, 12-byte nonce, \
and well-formed plaintext is infallible",
);
let (ct, tag) = ct_with_tag.split_at(ct_with_tag.len() - AUTH_TAG_LENGTH);
let mut envelope = Vec::with_capacity(HEADER_LENGTH + ct.len());
envelope.push(ENCRYPTION_VERSION_V2);
envelope.extend_from_slice(&self.salt);
envelope.extend_from_slice(&iv);
envelope.extend_from_slice(tag);
envelope.extend_from_slice(ct);
BASE64_STANDARD.encode(&envelope)
}
pub fn decrypt(&self, base64_envelope: &str) -> Result<String, StorageEncryptionError> {
let parsed = parse_envelope(base64_envelope)?;
if parsed.salt != self.salt {
return Err(StorageEncryptionError::Decrypt);
}
decrypt_with_aead(&self.aead, &parsed)
}
}
#[derive(Debug, Clone)]
pub struct EnvelopeParts {
pub version: u8,
pub salt: Salt,
pub iv: [u8; IV_LENGTH],
pub tag: [u8; AUTH_TAG_LENGTH],
pub ciphertext: Vec<u8>,
}
pub fn parse_envelope(base64_envelope: &str) -> Result<EnvelopeParts, StorageEncryptionError> {
let bytes = BASE64_STANDARD
.decode(base64_envelope.trim())
.map_err(StorageEncryptionError::InvalidBase64)?;
if bytes.len() < HEADER_LENGTH {
return Err(StorageEncryptionError::TooShort(bytes.len()));
}
let version = bytes[0];
if version != ENCRYPTION_VERSION_V1 && version != ENCRYPTION_VERSION_V2 {
return Err(StorageEncryptionError::UnsupportedVersion(version));
}
let mut salt = [0u8; SALT_LENGTH];
salt.copy_from_slice(&bytes[1..=SALT_LENGTH]);
let mut iv = [0u8; IV_LENGTH];
iv.copy_from_slice(&bytes[1 + SALT_LENGTH..1 + SALT_LENGTH + IV_LENGTH]);
let mut tag = [0u8; AUTH_TAG_LENGTH];
tag.copy_from_slice(
&bytes[1 + SALT_LENGTH + IV_LENGTH..1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH],
);
let ciphertext = bytes[HEADER_LENGTH..].to_vec();
Ok(EnvelopeParts {
version,
salt,
iv,
tag,
ciphertext,
})
}
#[allow(deprecated)]
pub fn decrypt_with_key(
key: &[u8; KEY_LENGTH],
parts: &EnvelopeParts,
) -> Result<String, StorageEncryptionError> {
let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
decrypt_with_aead(&aead, parts)
}
#[allow(deprecated)]
fn decrypt_with_aead(
aead: &Aes256Gcm,
parts: &EnvelopeParts,
) -> Result<String, StorageEncryptionError> {
let mut combined = Vec::with_capacity(parts.ciphertext.len() + AUTH_TAG_LENGTH);
combined.extend_from_slice(&parts.ciphertext);
combined.extend_from_slice(&parts.tag);
let plaintext = aead
.decrypt(
Nonce::from_slice(&parts.iv),
Payload {
msg: &combined,
aad: &[],
},
)
.map_err(|_| StorageEncryptionError::Decrypt)?;
String::from_utf8(plaintext).map_err(|_| StorageEncryptionError::Decrypt)
}
#[must_use]
pub fn is_encrypted(data: &str) -> bool {
let Ok(bytes) = BASE64_STANDARD.decode(data.trim()) else {
return false;
};
bytes.len() >= HEADER_LENGTH
&& (bytes[0] == ENCRYPTION_VERSION_V1 || bytes[0] == ENCRYPTION_VERSION_V2)
}
pub fn get_version(data: &str) -> Result<u8, StorageEncryptionError> {
let bytes = BASE64_STANDARD
.decode(data.trim())
.map_err(StorageEncryptionError::InvalidBase64)?;
if bytes.is_empty() {
return Err(StorageEncryptionError::TooShort(0));
}
Ok(bytes[0])
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::StdRng;
use rand::SeedableRng;
fn rng(seed: u64) -> StdRng {
StdRng::seed_from_u64(seed)
}
#[test]
fn header_length_matches_ts_constant() {
assert_eq!(HEADER_LENGTH, 61);
}
#[test]
fn pbkdf2_iteration_constants_match_ts() {
assert_eq!(PBKDF2_ITERATIONS_V1, 100_000);
assert_eq!(PBKDF2_ITERATIONS_V2, 600_000);
}
#[test]
fn round_trip_encrypt_then_decrypt_with_same_cipher() {
let mut r = rng(0x42);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let plain = "this is the plaintext that should round-trip cleanly";
let envelope = cipher.encrypt(&mut r, plain);
assert!(is_encrypted(&envelope));
let recovered = cipher.decrypt(&envelope).expect("round-trip decrypt");
assert_eq!(recovered, plain);
}
#[test]
fn round_trip_via_importer_path_using_envelope_salt() {
let mut r = rng(0x99);
let pw = "TheQuickBrownFox-12345!";
let cipher = Cipher::derive(&mut r, pw);
let plain = "import-path round-trip";
let envelope = cipher.encrypt(&mut r, plain);
let parts = parse_envelope(&envelope).unwrap();
let importer = Cipher::derive_for_version(pw, &parts.salt, parts.version).unwrap();
let recovered = importer.decrypt(&envelope).unwrap();
assert_eq!(recovered, plain);
}
#[test]
fn wrong_password_rejects_with_decrypt_error() {
let mut r = rng(1);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let envelope = cipher.encrypt(&mut r, "some payload");
let parts = parse_envelope(&envelope).unwrap();
let wrong = Cipher::derive_for_version(
"DifferentPassword!12345",
&parts.salt,
ENCRYPTION_VERSION_V2,
)
.unwrap();
let err = wrong.decrypt(&envelope).unwrap_err();
assert!(matches!(err, StorageEncryptionError::Decrypt));
}
#[test]
fn truncated_envelope_rejects_with_too_short() {
let truncated = BASE64_STANDARD.encode([0u8; HEADER_LENGTH - 1]);
let err = parse_envelope(&truncated).unwrap_err();
assert!(matches!(err, StorageEncryptionError::TooShort(_)));
}
#[test]
fn unsupported_version_rejects() {
let mut bytes = vec![0xFFu8]; bytes.extend(vec![0u8; HEADER_LENGTH - 1]);
let envelope = BASE64_STANDARD.encode(bytes);
let err = parse_envelope(&envelope).unwrap_err();
assert!(matches!(
err,
StorageEncryptionError::UnsupportedVersion(0xFF)
));
}
#[test]
fn corrupted_ciphertext_rejects_with_decrypt_error() {
let mut r = rng(2);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let envelope = cipher.encrypt(&mut r, "payload");
let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
let last = decoded.len() - 1;
decoded[last] ^= 0xff;
let tampered = BASE64_STANDARD.encode(&decoded);
let err = cipher.decrypt(&tampered).unwrap_err();
assert!(matches!(err, StorageEncryptionError::Decrypt));
}
#[test]
fn corrupted_tag_rejects_with_decrypt_error() {
let mut r = rng(3);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let envelope = cipher.encrypt(&mut r, "payload");
let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
let tag_start = 1 + SALT_LENGTH + IV_LENGTH;
decoded[tag_start] ^= 0xff;
let tampered = BASE64_STANDARD.encode(&decoded);
let err = cipher.decrypt(&tampered).unwrap_err();
assert!(matches!(err, StorageEncryptionError::Decrypt));
}
#[test]
fn invalid_base64_rejects() {
let err = parse_envelope("@@@not-base64@@@").unwrap_err();
assert!(matches!(err, StorageEncryptionError::InvalidBase64(_)));
}
#[test]
fn is_encrypted_recognises_well_formed_envelope() {
let mut r = rng(4);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let envelope = cipher.encrypt(&mut r, "x");
assert!(is_encrypted(&envelope));
}
#[test]
fn is_encrypted_rejects_random_string() {
let bogus = BASE64_STANDARD.encode([0x99u8; HEADER_LENGTH + 4]);
assert!(!is_encrypted(&bogus));
}
#[test]
fn get_version_returns_emitted_version() {
let mut r = rng(5);
let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
let envelope = cipher.encrypt(&mut r, "x");
assert_eq!(get_version(&envelope).unwrap(), ENCRYPTION_VERSION_V2);
}
#[test]
fn distinct_salts_distinct_envelopes_for_same_plaintext() {
let mut r1 = rng(10);
let mut r2 = rng(11);
let c1 = Cipher::derive(&mut r1, "TheQuickBrownFox-12345!");
let c2 = Cipher::derive(&mut r2, "TheQuickBrownFox-12345!");
assert_ne!(c1.salt, c2.salt);
let e1 = c1.encrypt(&mut r1, "same plain");
let e2 = c2.encrypt(&mut r2, "same plain");
assert_ne!(e1, e2);
}
#[test]
fn pbkdf2_v2_known_answer_against_rfc6070_style_vector() {
let mut out = [0u8; 32];
pbkdf2::pbkdf2::<Hmac<Sha256>>(b"password", b"salt", 1, &mut out).unwrap();
let expected =
hex::decode("120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b")
.unwrap();
assert_eq!(out.as_slice(), expected.as_slice());
}
}