moonproof_contracts/providers/
storage_encryption.rs1use aes_gcm::aead::{Aead, KeyInit, Payload};
48use aes_gcm::{Aes256Gcm, Key, Nonce};
49use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
50use base64::Engine as _;
51use hmac::Hmac;
52use sha2::Sha256;
53use thiserror::Error;
54
55pub const KEY_LENGTH: usize = 32;
57pub const IV_LENGTH: usize = 12;
61pub const AUTH_TAG_LENGTH: usize = 16;
63pub const SALT_LENGTH: usize = 32;
66
67pub const PBKDF2_ITERATIONS_V1: u32 = 100_000;
71pub const PBKDF2_ITERATIONS_V2: u32 = 600_000;
74
75pub const ENCRYPTION_VERSION_V1: u8 = 1;
77pub const ENCRYPTION_VERSION_V2: u8 = 2;
80pub const HEADER_LENGTH: usize = 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
83
84#[derive(Debug, Error)]
92pub enum StorageEncryptionError {
93 #[error("invalid encrypted data: too short ({0} bytes, header is 61 bytes)")]
96 TooShort(usize),
97 #[error("unsupported encryption version: {0}")]
100 UnsupportedVersion(u8),
101 #[error("invalid base64: {0}")]
103 InvalidBase64(#[source] base64::DecodeError),
104 #[error("decryption failed (wrong password or corrupted ciphertext)")]
108 Decrypt,
109}
110
111pub type Salt = [u8; SALT_LENGTH];
118
119#[derive(Clone)]
127pub struct Cipher {
128 aead: Aes256Gcm,
129 salt: Salt,
130}
131
132impl Cipher {
133 pub fn derive<R: rand::CryptoRng + rand::RngCore>(rng: &mut R, password: &str) -> Self {
137 let mut salt = [0u8; SALT_LENGTH];
138 rng.fill_bytes(&mut salt);
139 Self::derive_with_salt(password, &salt, PBKDF2_ITERATIONS_V2)
140 }
141
142 #[allow(deprecated)]
147 pub fn derive_with_salt(password: &str, salt: &Salt, iterations: u32) -> Self {
148 let mut key = [0u8; KEY_LENGTH];
149 pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), salt, iterations, &mut key)
155 .expect("PBKDF2 with a 32-byte key length is infallible");
156 let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));
159 Self { aead, salt: *salt }
160 }
161
162 pub fn derive_for_version(
166 password: &str,
167 salt: &Salt,
168 version: u8,
169 ) -> Result<Self, StorageEncryptionError> {
170 let iterations = match version {
171 ENCRYPTION_VERSION_V1 => PBKDF2_ITERATIONS_V1,
172 ENCRYPTION_VERSION_V2 => PBKDF2_ITERATIONS_V2,
173 other => return Err(StorageEncryptionError::UnsupportedVersion(other)),
174 };
175 Ok(Self::derive_with_salt(password, salt, iterations))
176 }
177
178 #[must_use]
180 pub fn salt(&self) -> &Salt {
181 &self.salt
182 }
183
184 #[allow(deprecated)]
187 pub fn encrypt<R: rand::CryptoRng + rand::RngCore>(
188 &self,
189 rng: &mut R,
190 plaintext: &str,
191 ) -> String {
192 let mut iv = [0u8; IV_LENGTH];
193 rng.fill_bytes(&mut iv);
194 let ct_with_tag = self
197 .aead
198 .encrypt(
199 Nonce::from_slice(&iv),
200 Payload {
201 msg: plaintext.as_bytes(),
202 aad: &[],
203 },
204 )
205 .expect(
206 "AES-256-GCM encryption with a 32-byte key, 12-byte nonce, \
207 and well-formed plaintext is infallible",
208 );
209 let (ct, tag) = ct_with_tag.split_at(ct_with_tag.len() - AUTH_TAG_LENGTH);
214 let mut envelope = Vec::with_capacity(HEADER_LENGTH + ct.len());
215 envelope.push(ENCRYPTION_VERSION_V2);
216 envelope.extend_from_slice(&self.salt);
217 envelope.extend_from_slice(&iv);
218 envelope.extend_from_slice(tag);
219 envelope.extend_from_slice(ct);
220 BASE64_STANDARD.encode(&envelope)
221 }
222
223 pub fn decrypt(&self, base64_envelope: &str) -> Result<String, StorageEncryptionError> {
229 let parsed = parse_envelope(base64_envelope)?;
230 if parsed.salt != self.salt {
231 return Err(StorageEncryptionError::Decrypt);
239 }
240 decrypt_with_aead(&self.aead, &parsed)
241 }
242}
243
244#[derive(Debug, Clone)]
246pub struct EnvelopeParts {
247 pub version: u8,
248 pub salt: Salt,
249 pub iv: [u8; IV_LENGTH],
250 pub tag: [u8; AUTH_TAG_LENGTH],
251 pub ciphertext: Vec<u8>,
252}
253
254pub fn parse_envelope(base64_envelope: &str) -> Result<EnvelopeParts, StorageEncryptionError> {
260 let bytes = BASE64_STANDARD
261 .decode(base64_envelope.trim())
262 .map_err(StorageEncryptionError::InvalidBase64)?;
263 if bytes.len() < HEADER_LENGTH {
264 return Err(StorageEncryptionError::TooShort(bytes.len()));
265 }
266 let version = bytes[0];
267 if version != ENCRYPTION_VERSION_V1 && version != ENCRYPTION_VERSION_V2 {
268 return Err(StorageEncryptionError::UnsupportedVersion(version));
269 }
270 let mut salt = [0u8; SALT_LENGTH];
271 salt.copy_from_slice(&bytes[1..=SALT_LENGTH]);
272 let mut iv = [0u8; IV_LENGTH];
273 iv.copy_from_slice(&bytes[1 + SALT_LENGTH..1 + SALT_LENGTH + IV_LENGTH]);
274 let mut tag = [0u8; AUTH_TAG_LENGTH];
275 tag.copy_from_slice(
276 &bytes[1 + SALT_LENGTH + IV_LENGTH..1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH],
277 );
278 let ciphertext = bytes[HEADER_LENGTH..].to_vec();
279 Ok(EnvelopeParts {
280 version,
281 salt,
282 iv,
283 tag,
284 ciphertext,
285 })
286}
287
288#[allow(deprecated)]
292pub fn decrypt_with_key(
293 key: &[u8; KEY_LENGTH],
294 parts: &EnvelopeParts,
295) -> Result<String, StorageEncryptionError> {
296 let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
297 decrypt_with_aead(&aead, parts)
298}
299
300#[allow(deprecated)]
301fn decrypt_with_aead(
302 aead: &Aes256Gcm,
303 parts: &EnvelopeParts,
304) -> Result<String, StorageEncryptionError> {
305 let mut combined = Vec::with_capacity(parts.ciphertext.len() + AUTH_TAG_LENGTH);
308 combined.extend_from_slice(&parts.ciphertext);
309 combined.extend_from_slice(&parts.tag);
310 let plaintext = aead
311 .decrypt(
312 Nonce::from_slice(&parts.iv),
313 Payload {
314 msg: &combined,
315 aad: &[],
316 },
317 )
318 .map_err(|_| StorageEncryptionError::Decrypt)?;
319 String::from_utf8(plaintext).map_err(|_| StorageEncryptionError::Decrypt)
320}
321
322#[must_use]
325pub fn is_encrypted(data: &str) -> bool {
326 let Ok(bytes) = BASE64_STANDARD.decode(data.trim()) else {
327 return false;
328 };
329 bytes.len() >= HEADER_LENGTH
330 && (bytes[0] == ENCRYPTION_VERSION_V1 || bytes[0] == ENCRYPTION_VERSION_V2)
331}
332
333pub fn get_version(data: &str) -> Result<u8, StorageEncryptionError> {
336 let bytes = BASE64_STANDARD
337 .decode(data.trim())
338 .map_err(StorageEncryptionError::InvalidBase64)?;
339 if bytes.is_empty() {
340 return Err(StorageEncryptionError::TooShort(0));
341 }
342 Ok(bytes[0])
343}
344
345#[cfg(test)]
346mod tests {
347 use super::*;
348 use rand::rngs::StdRng;
349 use rand::SeedableRng;
350
351 fn rng(seed: u64) -> StdRng {
352 StdRng::seed_from_u64(seed)
353 }
354
355 #[test]
356 fn header_length_matches_ts_constant() {
357 assert_eq!(HEADER_LENGTH, 61);
359 }
360
361 #[test]
362 fn pbkdf2_iteration_constants_match_ts() {
363 assert_eq!(PBKDF2_ITERATIONS_V1, 100_000);
364 assert_eq!(PBKDF2_ITERATIONS_V2, 600_000);
365 }
366
367 #[test]
368 fn round_trip_encrypt_then_decrypt_with_same_cipher() {
369 let mut r = rng(0x42);
370 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
371 let plain = "this is the plaintext that should round-trip cleanly";
372 let envelope = cipher.encrypt(&mut r, plain);
373 assert!(is_encrypted(&envelope));
374 let recovered = cipher.decrypt(&envelope).expect("round-trip decrypt");
375 assert_eq!(recovered, plain);
376 }
377
378 #[test]
379 fn round_trip_via_importer_path_using_envelope_salt() {
380 let mut r = rng(0x99);
383 let pw = "TheQuickBrownFox-12345!";
384 let cipher = Cipher::derive(&mut r, pw);
385 let plain = "import-path round-trip";
386 let envelope = cipher.encrypt(&mut r, plain);
387
388 let parts = parse_envelope(&envelope).unwrap();
389 let importer = Cipher::derive_for_version(pw, &parts.salt, parts.version).unwrap();
390 let recovered = importer.decrypt(&envelope).unwrap();
391 assert_eq!(recovered, plain);
392 }
393
394 #[test]
395 fn wrong_password_rejects_with_decrypt_error() {
396 let mut r = rng(1);
397 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
398 let envelope = cipher.encrypt(&mut r, "some payload");
399 let parts = parse_envelope(&envelope).unwrap();
401 let wrong = Cipher::derive_for_version(
402 "DifferentPassword!12345",
403 &parts.salt,
404 ENCRYPTION_VERSION_V2,
405 )
406 .unwrap();
407 let err = wrong.decrypt(&envelope).unwrap_err();
408 assert!(matches!(err, StorageEncryptionError::Decrypt));
409 }
410
411 #[test]
412 fn truncated_envelope_rejects_with_too_short() {
413 let truncated = BASE64_STANDARD.encode([0u8; HEADER_LENGTH - 1]);
415 let err = parse_envelope(&truncated).unwrap_err();
416 assert!(matches!(err, StorageEncryptionError::TooShort(_)));
417 }
418
419 #[test]
420 fn unsupported_version_rejects() {
421 let mut bytes = vec![0xFFu8]; bytes.extend(vec![0u8; HEADER_LENGTH - 1]);
423 let envelope = BASE64_STANDARD.encode(bytes);
424 let err = parse_envelope(&envelope).unwrap_err();
425 assert!(matches!(
426 err,
427 StorageEncryptionError::UnsupportedVersion(0xFF)
428 ));
429 }
430
431 #[test]
432 fn corrupted_ciphertext_rejects_with_decrypt_error() {
433 let mut r = rng(2);
434 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
435 let envelope = cipher.encrypt(&mut r, "payload");
436
437 let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
439 let last = decoded.len() - 1;
440 decoded[last] ^= 0xff;
441 let tampered = BASE64_STANDARD.encode(&decoded);
442
443 let err = cipher.decrypt(&tampered).unwrap_err();
444 assert!(matches!(err, StorageEncryptionError::Decrypt));
445 }
446
447 #[test]
448 fn corrupted_tag_rejects_with_decrypt_error() {
449 let mut r = rng(3);
450 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
451 let envelope = cipher.encrypt(&mut r, "payload");
452
453 let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
456 let tag_start = 1 + SALT_LENGTH + IV_LENGTH;
457 decoded[tag_start] ^= 0xff;
458 let tampered = BASE64_STANDARD.encode(&decoded);
459
460 let err = cipher.decrypt(&tampered).unwrap_err();
461 assert!(matches!(err, StorageEncryptionError::Decrypt));
462 }
463
464 #[test]
465 fn invalid_base64_rejects() {
466 let err = parse_envelope("@@@not-base64@@@").unwrap_err();
467 assert!(matches!(err, StorageEncryptionError::InvalidBase64(_)));
468 }
469
470 #[test]
471 fn is_encrypted_recognises_well_formed_envelope() {
472 let mut r = rng(4);
473 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
474 let envelope = cipher.encrypt(&mut r, "x");
475 assert!(is_encrypted(&envelope));
476 }
477
478 #[test]
479 fn is_encrypted_rejects_random_string() {
480 let bogus = BASE64_STANDARD.encode([0x99u8; HEADER_LENGTH + 4]);
482 assert!(!is_encrypted(&bogus));
483 }
484
485 #[test]
486 fn get_version_returns_emitted_version() {
487 let mut r = rng(5);
488 let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
489 let envelope = cipher.encrypt(&mut r, "x");
490 assert_eq!(get_version(&envelope).unwrap(), ENCRYPTION_VERSION_V2);
491 }
492
493 #[test]
494 fn distinct_salts_distinct_envelopes_for_same_plaintext() {
495 let mut r1 = rng(10);
499 let mut r2 = rng(11);
500 let c1 = Cipher::derive(&mut r1, "TheQuickBrownFox-12345!");
501 let c2 = Cipher::derive(&mut r2, "TheQuickBrownFox-12345!");
502 assert_ne!(c1.salt, c2.salt);
503 let e1 = c1.encrypt(&mut r1, "same plain");
504 let e2 = c2.encrypt(&mut r2, "same plain");
505 assert_ne!(e1, e2);
506 }
507
508 #[test]
509 fn pbkdf2_v2_known_answer_against_rfc6070_style_vector() {
510 let mut out = [0u8; 32];
517 pbkdf2::pbkdf2::<Hmac<Sha256>>(b"password", b"salt", 1, &mut out).unwrap();
518 let expected =
519 hex::decode("120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b")
520 .unwrap();
521 assert_eq!(out.as_slice(), expected.as_slice());
522 }
523}