π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
rust/validation: add crypto validation tests
Prateek Sunal4ccd2545539c
diff --git a/rust/validation/src/tests/argon2.rs b/rust/validation/src/tests/argon2.rsnew file mode 100644index 0000000000..da9278c795--- /dev/null+++ b/rust/validation/src/tests/argon2.rs@@ -0,0 +1,153 @@+//! Argon2id validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;++pub fn run_all() -> TestResult {+ println!("\nββ Argon2id Key Derivation ββ");+ run_tests! {+ "Interactive params (64MB, 2 ops)" => test_interactive_params(),+ "Moderate params (256MB, 3 ops)" => test_moderate_params(),+ "Custom params" => test_custom_params(),+ "Different passwords" => test_different_passwords(),+ "Different salts" => test_different_salts(),+ "Unicode password" => test_unicode_password(),+ "Empty password" => test_empty_password(),+ "Long password" => test_long_password(),+ }+}++fn derive_libsodium(password: &str, salt: &[u8], mem_limit: u32, ops_limit: u32) -> Vec<u8> {+ let mut key = vec![0u8; 32];+ let result = unsafe {+ sodium::crypto_pwhash(+ key.as_mut_ptr(),+ 32,+ password.as_ptr() as *const i8,+ password.len() as u64,+ salt.as_ptr(),+ ops_limit as u64,+ mem_limit as usize,+ sodium::crypto_pwhash_ALG_ARGON2ID13 as i32,+ )+ };+ assert_eq!(result, 0, "libsodium argon2 failed");+ key+}++fn test_interactive_params() -> bool {+ let password = "test_password";+ let salt = crate::random_bytes(16);+ let mem = 67108864; // 64MB+ let ops = 2;++ let libsodium_key = derive_libsodium(password, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(password, &salt, mem, ops).unwrap();++ libsodium_key == core_key+}++fn test_moderate_params() -> bool {+ let password = "moderate_password";+ let salt = crate::random_bytes(16);+ let mem = 268435456; // 256MB+ let ops = 3;++ let libsodium_key = derive_libsodium(password, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(password, &salt, mem, ops).unwrap();++ libsodium_key == core_key+}++fn test_custom_params() -> bool {+ let password = "custom";+ let salt = crate::random_bytes(16);++ // Test various param combinations+ for (mem, ops) in [+ (32 * 1024 * 1024, 1),+ (128 * 1024 * 1024, 4),+ (64 * 1024 * 1024, 3),+ ] {+ let libsodium_key = derive_libsodium(password, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(password, &salt, mem, ops).unwrap();+ if libsodium_key != core_key {+ return false;+ }+ }+ true+}++fn test_different_passwords() -> bool {+ let salt = crate::random_bytes(16);+ let mem = 67108864;+ let ops = 2;++ let passwords = ["password1", "password2", "p@ssw0rd!", ""];++ for p in &passwords {+ let libsodium_key = derive_libsodium(p, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(p, &salt, mem, ops).unwrap();+ if libsodium_key != core_key {+ return false;+ }+ }+ true+}++fn test_different_salts() -> bool {+ let password = "password";+ let mem = 67108864;+ let ops = 2;++ for _ in 0..5 {+ let salt = crate::random_bytes(16);+ let libsodium_key = derive_libsodium(password, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(password, &salt, mem, ops).unwrap();+ if libsodium_key != core_key {+ return false;+ }+ }+ true+}++fn test_unicode_password() -> bool {+ let passwords = ["ΠΏΠ°ΡΠΎΠ»Ρ", "ε―η ", "πππ", "cafΓ©", "ζ₯ζ¬θͺ"];+ let salt = crate::random_bytes(16);+ let mem = 67108864;+ let ops = 2;++ for p in &passwords {+ let libsodium_key = derive_libsodium(p, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(p, &salt, mem, ops).unwrap();+ if libsodium_key != core_key {+ return false;+ }+ }+ true+}++fn test_empty_password() -> bool {+ let salt = crate::random_bytes(16);+ let mem = 67108864;+ let ops = 2;++ let libsodium_key = derive_libsodium("", &salt, mem, ops);+ let core_key = crypto::argon::derive_key("", &salt, mem, ops).unwrap();++ libsodium_key == core_key+}++fn test_long_password() -> bool {+ let password = "a".repeat(1000);+ let salt = crate::random_bytes(16);+ let mem = 67108864;+ let ops = 2;++ let libsodium_key = derive_libsodium(&password, &salt, mem, ops);+ let core_key = crypto::argon::derive_key(&password, &salt, mem, ops).unwrap();++ libsodium_key == core_key+}diff --git a/rust/validation/src/tests/auth_flow.rs b/rust/validation/src/tests/auth_flow.rsnew file mode 100644index 0000000000..f7fecf3e6c--- /dev/null+++ b/rust/validation/src/tests/auth_flow.rs@@ -0,0 +1,354 @@+//! Full authentication flow validation+//!+//! Tests the complete signup/login flow comparing ente-core with libsodium.++use super::TestResult;+use crate::run_tests;+use base64::{engine::general_purpose::STANDARD, Engine};+use ente_core::auth::{+ decrypt_secrets, derive_kek, generate_keys_with_strength, KeyDerivationStrength,+};+use ente_core::crypto;+use libsodium_sys as sodium;+use std::ffi::c_char;++pub fn run_all() -> TestResult {+ println!("\nββ Full Authentication Flow ββ");+ run_tests! {+ "Key generation produces valid keys" => test_key_generation(),+ "Login key matches between core and libsodium" => test_login_key_derivation(),+ "Decrypt secrets roundtrip" => test_decrypt_secrets(),+ "Recovery key roundtrip" => test_recovery_key(),+ "Password change flow" => test_password_change(),+ "Cross-implementation auth flow" => test_cross_impl_auth(),+ }+}++/// Derive KEK using libsodium+fn libsodium_derive_kek(password: &str, salt: &[u8], mem: u32, ops: u32) -> Vec<u8> {+ let mut key = vec![0u8; 32];+ let result = unsafe {+ sodium::crypto_pwhash(+ key.as_mut_ptr(),+ 32,+ password.as_ptr() as *const i8,+ password.len() as u64,+ salt.as_ptr(),+ ops as u64,+ mem as usize,+ sodium::crypto_pwhash_ALG_ARGON2ID13 as i32,+ )+ };+ assert_eq!(result, 0, "libsodium argon2 failed");+ key+}++/// Derive login key using libsodium KDF+fn libsodium_derive_login_key(kek: &[u8]) -> Vec<u8> {+ let mut subkey = vec![0u8; 32];+ let mut ctx = [0u8; 8];+ ctx[..8].copy_from_slice(b"loginctx");++ let result = unsafe {+ sodium::crypto_kdf_derive_from_key(+ subkey.as_mut_ptr(),+ 32,+ 1, // subkey_id+ ctx.as_ptr() as *const c_char,+ kek.as_ptr(),+ )+ };+ assert_eq!(result, 0, "libsodium kdf failed");+ subkey[..16].to_vec()+}++/// Encrypt with libsodium secretbox+#[allow(dead_code)]+fn libsodium_secretbox_seal(plaintext: &[u8], nonce: &[u8], key: &[u8]) -> Vec<u8> {+ let mut ciphertext = vec![0u8; plaintext.len() + 16];+ unsafe {+ sodium::crypto_secretbox_easy(+ ciphertext.as_mut_ptr(),+ plaintext.as_ptr(),+ plaintext.len() as u64,+ nonce.as_ptr(),+ key.as_ptr(),+ );+ }+ ciphertext+}++/// Decrypt with libsodium secretbox+fn libsodium_secretbox_open(ciphertext: &[u8], nonce: &[u8], key: &[u8]) -> Option<Vec<u8>> {+ if ciphertext.len() < 16 {+ return None;+ }+ let mut plaintext = vec![0u8; ciphertext.len() - 16];+ let result = unsafe {+ sodium::crypto_secretbox_open_easy(+ plaintext.as_mut_ptr(),+ ciphertext.as_ptr(),+ ciphertext.len() as u64,+ nonce.as_ptr(),+ key.as_ptr(),+ )+ };+ if result == 0 {+ Some(plaintext)+ } else {+ None+ }+}++/// Seal with libsodium sealed box+#[allow(dead_code)]+fn libsodium_seal(plaintext: &[u8], pk: &[u8]) -> Vec<u8> {+ let mut ciphertext = vec![0u8; plaintext.len() + 48];+ unsafe {+ sodium::crypto_box_seal(+ ciphertext.as_mut_ptr(),+ plaintext.as_ptr(),+ plaintext.len() as u64,+ pk.as_ptr(),+ );+ }+ ciphertext+}++fn test_key_generation() -> bool {+ crypto::init().unwrap();++ let password = "test_password_123!";+ let result = generate_keys_with_strength(password, KeyDerivationStrength::Interactive);++ if result.is_err() {+ return false;+ }++ let result = result.unwrap();++ // Verify all keys have correct lengths+ let master_key = crypto::decode_b64(&result.private_key_attributes.key).unwrap();+ let secret_key = crypto::decode_b64(&result.private_key_attributes.secret_key).unwrap();+ let public_key = crypto::decode_b64(&result.key_attributes.public_key).unwrap();++ master_key.len() == 32+ && secret_key.len() == 32+ && public_key.len() == 32+ && result.login_key.len() == 16+ && result.private_key_attributes.recovery_key.len() == 64 // hex encoded+}++fn test_login_key_derivation() -> bool {+ crypto::init().unwrap();++ let password = "login_test_password";+ let salt = crate::random_bytes(16);+ let mem = 67108864; // 64MB+ let ops = 2;++ // Derive KEK with both implementations+ let libsodium_kek = libsodium_derive_kek(password, &salt, mem, ops);+ let core_kek = crypto::argon::derive_key(password, &salt, mem, ops).unwrap();++ if libsodium_kek != core_kek {+ eprintln!(" KEK mismatch!");+ return false;+ }++ // Derive login key with both implementations+ let libsodium_login = libsodium_derive_login_key(&libsodium_kek);+ let core_login = crypto::kdf::derive_login_key(&core_kek).unwrap();++ if libsodium_login != core_login {+ eprintln!(" Login key mismatch!");+ eprintln!(" libsodium: {}", hex::encode(&libsodium_login));+ eprintln!(" core: {}", hex::encode(&core_login));+ return false;+ }++ true+}++fn test_decrypt_secrets() -> bool {+ crypto::init().unwrap();++ let password = "decrypt_test_password";++ // Generate keys with core+ let gen_result =+ generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();++ // Create a sealed token+ let token = b"test_auth_token_12345";+ let public_key = crypto::decode_b64(&gen_result.key_attributes.public_key).unwrap();+ let sealed_token = crypto::sealed::seal(token, &public_key).unwrap();+ let encrypted_token = STANDARD.encode(&sealed_token);++ // Decrypt with core+ let mem_limit = gen_result+ .key_attributes+ .mem_limit+ .expect("missing mem_limit");+ let ops_limit = gen_result+ .key_attributes+ .ops_limit+ .expect("missing ops_limit");+ let kek = derive_kek(+ password,+ &gen_result.key_attributes.kek_salt,+ mem_limit,+ ops_limit,+ )+ .unwrap();++ let result = decrypt_secrets(&kek, &gen_result.key_attributes, &encrypted_token);++ if result.is_err() {+ eprintln!(" Decrypt failed: {:?}", result.err());+ return false;+ }++ let result = result.unwrap();++ // Verify decrypted values+ let expected_master = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();+ let expected_secret =+ crypto::decode_b64(&gen_result.private_key_attributes.secret_key).unwrap();++ result.master_key == expected_master+ && result.secret_key == expected_secret+ && result.token == token+}++fn test_recovery_key() -> bool {+ crypto::init().unwrap();++ let password = "recovery_test_password";+ let gen_result =+ generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();++ // Get recovery key+ let recovery_key_hex = &gen_result.private_key_attributes.recovery_key;+ let recovery_key = crypto::decode_hex(recovery_key_hex).unwrap();++ // Verify recovery key can decrypt master key+ let enc_master = crypto::decode_b64(+ gen_result+ .key_attributes+ .master_key_encrypted_with_recovery_key+ .as_ref()+ .unwrap(),+ )+ .unwrap();+ let nonce = crypto::decode_b64(+ gen_result+ .key_attributes+ .master_key_decryption_nonce+ .as_ref()+ .unwrap(),+ )+ .unwrap();++ // Decrypt with libsodium+ let decrypted = libsodium_secretbox_open(&enc_master, &nonce, &recovery_key);++ if decrypted.is_none() {+ return false;+ }++ let expected_master = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();+ decrypted.unwrap() == expected_master+}++fn test_password_change() -> bool {+ crypto::init().unwrap();++ let old_password = "old_password_123";+ let new_password = "new_password_456";++ // Generate initial keys+ let gen_result =+ generate_keys_with_strength(old_password, KeyDerivationStrength::Interactive).unwrap();+ let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();++ // Generate new key attributes for new password+ let (new_attrs, new_login_key) =+ ente_core::auth::generate_key_attributes_for_new_password_with_strength(+ &master_key,+ new_password,+ KeyDerivationStrength::Interactive,+ )+ .unwrap();++ // Verify new login key is different+ if new_login_key == gen_result.login_key {+ return false;+ }++ // Verify can decrypt master key with new password using libsodium+ let new_salt = crypto::decode_b64(&new_attrs.kek_salt).unwrap();+ let new_kek = libsodium_derive_kek(+ new_password,+ &new_salt,+ new_attrs.mem_limit.unwrap(),+ new_attrs.ops_limit.unwrap(),+ );++ let enc_key = crypto::decode_b64(&new_attrs.encrypted_key).unwrap();+ let nonce = crypto::decode_b64(&new_attrs.key_decryption_nonce).unwrap();++ let decrypted = libsodium_secretbox_open(&enc_key, &nonce, &new_kek);++ decrypted == Some(master_key)+}++fn test_cross_impl_auth() -> bool {+ crypto::init().unwrap();++ let password = "cross_impl_password";++ // Simulate signup with core+ let gen_result =+ generate_keys_with_strength(password, KeyDerivationStrength::Interactive).unwrap();++ // Simulate server storing key attributes+ let key_attrs = &gen_result.key_attributes;++ // Simulate login with libsodium (like the CLI would do)+ let kek_salt = crypto::decode_b64(&key_attrs.kek_salt).unwrap();+ let kek = libsodium_derive_kek(+ password,+ &kek_salt,+ key_attrs.mem_limit.unwrap(),+ key_attrs.ops_limit.unwrap(),+ );++ // Decrypt master key with libsodium+ let enc_key = crypto::decode_b64(&key_attrs.encrypted_key).unwrap();+ let nonce = crypto::decode_b64(&key_attrs.key_decryption_nonce).unwrap();+ let master_key = libsodium_secretbox_open(&enc_key, &nonce, &kek);++ if master_key.is_none() {+ eprintln!(" Failed to decrypt master key with libsodium");+ return false;+ }+ let master_key = master_key.unwrap();++ // Decrypt secret key with libsodium+ let enc_secret = crypto::decode_b64(&key_attrs.encrypted_secret_key).unwrap();+ let secret_nonce = crypto::decode_b64(&key_attrs.secret_key_decryption_nonce).unwrap();+ let secret_key = libsodium_secretbox_open(&enc_secret, &secret_nonce, &master_key);++ if secret_key.is_none() {+ eprintln!(" Failed to decrypt secret key with libsodium");+ return false;+ }++ // Verify keys match+ let expected_master = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();+ let expected_secret =+ crypto::decode_b64(&gen_result.private_key_attributes.secret_key).unwrap();++ master_key == expected_master && secret_key.unwrap() == expected_secret+}diff --git a/rust/validation/src/tests/hash.rs b/rust/validation/src/tests/hash.rsnew file mode 100644index 0000000000..c26c07e4c6--- /dev/null+++ b/rust/validation/src/tests/hash.rs@@ -0,0 +1,138 @@+//! BLAKE2b hash validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;++pub fn run_all() -> TestResult {+ println!("\nββ BLAKE2b Hash ββ");+ run_tests! {+ "Default hash (64 bytes)" => test_default_hash(),+ "Custom output lengths" => test_custom_lengths(),+ "Keyed hash" => test_keyed_hash(),+ "Empty input" => test_empty_input(),+ "Large input (1MB)" => test_large_input(),+ "Known test vector" => test_known_vector(),+ "Random data (100 iterations)" => test_random_data(),+ }+}++fn libsodium_hash(data: &[u8], out_len: usize) -> Vec<u8> {+ let mut hash = vec![0u8; out_len];+ let result = unsafe {+ sodium::crypto_generichash(+ hash.as_mut_ptr(),+ out_len,+ data.as_ptr(),+ data.len() as u64,+ std::ptr::null(),+ 0,+ )+ };+ assert_eq!(result, 0, "libsodium hash failed");+ hash+}++fn libsodium_hash_keyed(data: &[u8], key: &[u8], out_len: usize) -> Vec<u8> {+ let mut hash = vec![0u8; out_len];+ let result = unsafe {+ sodium::crypto_generichash(+ hash.as_mut_ptr(),+ out_len,+ data.as_ptr(),+ data.len() as u64,+ key.as_ptr(),+ key.len(),+ )+ };+ assert_eq!(result, 0, "libsodium keyed hash failed");+ hash+}++fn test_default_hash() -> bool {+ let data = b"Hello, World!";++ let libsodium_hash = libsodium_hash(data, 64);+ let core_hash = crypto::hash::hash_default(data).unwrap();++ libsodium_hash == core_hash+}++fn test_custom_lengths() -> bool {+ let data = b"Custom length test";++ for len in [16, 24, 32, 48, 64] {+ let libsodium_h = libsodium_hash(data, len);+ let core_h = crypto::hash::hash(data, Some(len), None).unwrap();+ if libsodium_h != core_h {+ eprintln!(" Failed for length={}", len);+ return false;+ }+ }+ true+}++fn test_keyed_hash() -> bool {+ let data = b"Keyed hash test";+ let key = crate::random_bytes(32);++ let libsodium_h = libsodium_hash_keyed(data, &key, 64);+ let core_h = crypto::hash::hash(data, None, Some(&key)).unwrap();++ libsodium_h == core_h+}++fn test_empty_input() -> bool {+ let data = b"";++ let libsodium_h = libsodium_hash(data, 64);+ let core_h = crypto::hash::hash_default(data).unwrap();++ libsodium_h == core_h+}++fn test_large_input() -> bool {+ let data = crate::random_bytes(1024 * 1024); // 1MB++ let libsodium_h = libsodium_hash(&data, 64);+ let core_h = crypto::hash::hash_default(&data).unwrap();++ libsodium_h == core_h+}++fn test_known_vector() -> bool {+ // BLAKE2b test vector from RFC 7693+ let data = b"abc";++ let libsodium_h = libsodium_hash(data, 64);+ let core_h = crypto::hash::hash_default(data).unwrap();++ // Both should match+ if libsodium_h != core_h {+ return false;+ }++ // Check known value (BLAKE2b-512 of "abc")+ let expected = hex::decode(+ "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1\+ 7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923",+ )+ .unwrap();++ libsodium_h == expected && core_h == expected+}++fn test_random_data() -> bool {+ for _ in 0..100 {+ let data = crate::random_bytes(rand::random::<usize>() % 10000 + 1);++ let libsodium_h = libsodium_hash(&data, 64);+ let core_h = crypto::hash::hash_default(&data).unwrap();++ if libsodium_h != core_h {+ return false;+ }+ }+ true+}diff --git a/rust/validation/src/tests/kdf.rs b/rust/validation/src/tests/kdf.rsnew file mode 100644index 0000000000..7b42d944fc--- /dev/null+++ b/rust/validation/src/tests/kdf.rs@@ -0,0 +1,155 @@+//! KDF (BLAKE2b) validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;+use std::ffi::c_char;++pub fn run_all() -> TestResult {+ println!("\nββ KDF (BLAKE2b) Subkey Derivation ββ");+ run_tests! {+ "Login key derivation (context='loginctx', id=1)" => test_login_key(),+ "Different subkey IDs" => test_different_ids(),+ "Different contexts" => test_different_contexts(),+ "Different subkey lengths" => test_different_lengths(),+ "Context truncation (>8 bytes)" => test_context_truncation(),+ "Context padding (<8 bytes)" => test_context_padding(),+ "Empty context" => test_empty_context(),+ "Random master keys" => test_random_keys(),+ }+}++fn derive_libsodium(key: &[u8], subkey_len: usize, subkey_id: u64, context: &[u8]) -> Vec<u8> {+ let mut subkey = vec![0u8; subkey_len];++ // Context must be exactly 8 bytes, zero-padded+ let mut ctx = [0u8; 8];+ let ctx_len = context.len().min(8);+ ctx[..ctx_len].copy_from_slice(&context[..ctx_len]);++ let result = unsafe {+ sodium::crypto_kdf_derive_from_key(+ subkey.as_mut_ptr(),+ subkey_len,+ subkey_id,+ ctx.as_ptr() as *const c_char,+ key.as_ptr(),+ )+ };+ assert_eq!(result, 0, "libsodium kdf failed");+ subkey+}++fn test_login_key() -> bool {+ // Test vector used in ente's login flow+ let master_key =+ hex::decode("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap();++ let libsodium_subkey = derive_libsodium(&master_key, 32, 1, b"loginctx");+ let libsodium_login_key = &libsodium_subkey[..16];++ let core_login_key = crypto::kdf::derive_login_key(&master_key).unwrap();++ libsodium_login_key == core_login_key.as_slice()+}++fn test_different_ids() -> bool {+ let master_key = crate::random_bytes(32);++ for id in [0, 1, 2, 100, u64::MAX] {+ let libsodium_key = derive_libsodium(&master_key, 32, id, b"testctx");+ let core_key = crypto::kdf::derive_subkey(&master_key, 32, id, b"testctx").unwrap();+ if libsodium_key != core_key {+ eprintln!(" Failed for id={}", id);+ return false;+ }+ }+ true+}++fn test_different_contexts() -> bool {+ let master_key = crate::random_bytes(32);++ let contexts: &[&[u8]] = &[b"context1", b"context2", b"test", b"loginctx", b"ABCDEFGH"];++ for ctx in contexts {+ let libsodium_key = derive_libsodium(&master_key, 32, 1, ctx);+ let core_key = crypto::kdf::derive_subkey(&master_key, 32, 1, ctx).unwrap();+ if libsodium_key != core_key {+ eprintln!(" Failed for context={:?}", String::from_utf8_lossy(ctx));+ return false;+ }+ }+ true+}++fn test_different_lengths() -> bool {+ let master_key = crate::random_bytes(32);++ for len in [16, 24, 32, 48, 64] {+ let libsodium_key = derive_libsodium(&master_key, len, 1, b"testctx");+ let core_key = crypto::kdf::derive_subkey(&master_key, len, 1, b"testctx").unwrap();+ if libsodium_key != core_key {+ eprintln!(" Failed for len={}", len);+ return false;+ }+ }+ true+}++fn test_context_truncation() -> bool {+ let master_key = crate::random_bytes(32);++ // Context > 8 bytes should be truncated to first 8+ let long_ctx = b"verylongcontext";+ let truncated_ctx = b"verylong"; // first 8 bytes++ let libsodium_long = derive_libsodium(&master_key, 32, 1, long_ctx);+ let libsodium_truncated = derive_libsodium(&master_key, 32, 1, truncated_ctx);+ let core_long = crypto::kdf::derive_subkey(&master_key, 32, 1, long_ctx).unwrap();++ // All three should be equal+ libsodium_long == libsodium_truncated && libsodium_long == core_long+}++fn test_context_padding() -> bool {+ let master_key = crate::random_bytes(32);++ // Short contexts should be zero-padded+ let short_contexts: &[&[u8]] = &[b"a", b"ab", b"abc", b"test"];++ for ctx in short_contexts {+ let libsodium_key = derive_libsodium(&master_key, 32, 1, ctx);+ let core_key = crypto::kdf::derive_subkey(&master_key, 32, 1, ctx).unwrap();+ if libsodium_key != core_key {+ eprintln!(+ " Failed for short context={:?}",+ String::from_utf8_lossy(ctx)+ );+ return false;+ }+ }+ true+}++fn test_empty_context() -> bool {+ let master_key = crate::random_bytes(32);++ let libsodium_key = derive_libsodium(&master_key, 32, 1, b"");+ let core_key = crypto::kdf::derive_subkey(&master_key, 32, 1, b"").unwrap();++ libsodium_key == core_key+}++fn test_random_keys() -> bool {+ for _ in 0..10 {+ let master_key = crate::random_bytes(32);+ let libsodium_key = derive_libsodium(&master_key, 32, 1, b"randtest");+ let core_key = crypto::kdf::derive_subkey(&master_key, 32, 1, b"randtest").unwrap();+ if libsodium_key != core_key {+ return false;+ }+ }+ true+}diff --git a/rust/validation/src/tests/mod.rs b/rust/validation/src/tests/mod.rsnew file mode 100644index 0000000000..ee4456c485--- /dev/null+++ b/rust/validation/src/tests/mod.rs@@ -0,0 +1,35 @@+pub mod argon2;+pub mod auth_flow;+pub mod hash;+pub mod kdf;+pub mod sealed;+pub mod secretbox;+pub mod stream;++/// Test result: (passed, failed)+pub type TestResult = (usize, usize);++/// Run a single test, print result, return success+pub fn run_test(name: &str, test_fn: impl FnOnce() -> bool) -> bool {+ let result = test_fn();+ let status = if result { "β" } else { "β" };+ println!(" {status} {name}");+ result+}++/// Helper macro for running multiple tests+#[macro_export]+macro_rules! run_tests {+ ($($name:expr => $test:expr),* $(,)?) => {{+ let mut passed = 0;+ let mut failed = 0;+ $(+ if $crate::tests::run_test($name, || $test) {+ passed += 1;+ } else {+ failed += 1;+ }+ )*+ (passed, failed)+ }};+}diff --git a/rust/validation/src/tests/sealed.rs b/rust/validation/src/tests/sealed.rsnew file mode 100644index 0000000000..7f21d0b858--- /dev/null+++ b/rust/validation/src/tests/sealed.rs@@ -0,0 +1,167 @@+//! SealedBox (X25519 + XSalsa20-Poly1305) validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;++const PUBLIC_KEY_BYTES: usize = 32;+const SECRET_KEY_BYTES: usize = 32;+const SEAL_BYTES: usize = 48; // 32 (ephemeral pk) + 16 (MAC)++pub fn run_all() -> TestResult {+ println!("\nββ SealedBox (X25519 + XSalsa20-Poly1305) ββ");+ run_tests! {+ "Keypair generation compatible" => test_keypair_generation(),+ "Core seal, libsodium open" => test_core_to_libsodium(),+ "Libsodium seal, core open" => test_libsodium_to_core(),+ "Empty plaintext" => test_empty_plaintext(),+ "Large plaintext (1MB)" => test_large_plaintext(),+ "Random data (50 iterations)" => test_random_data(),+ "Wrong key fails" => test_wrong_key(),+ }+}++fn libsodium_keypair() -> (Vec<u8>, Vec<u8>) {+ let mut pk = vec![0u8; PUBLIC_KEY_BYTES];+ let mut sk = vec![0u8; SECRET_KEY_BYTES];+ unsafe {+ sodium::crypto_box_keypair(pk.as_mut_ptr(), sk.as_mut_ptr());+ }+ (pk, sk)+}++fn libsodium_seal(plaintext: &[u8], recipient_pk: &[u8]) -> Vec<u8> {+ let mut ciphertext = vec![0u8; plaintext.len() + SEAL_BYTES];+ let result = unsafe {+ sodium::crypto_box_seal(+ ciphertext.as_mut_ptr(),+ plaintext.as_ptr(),+ plaintext.len() as u64,+ recipient_pk.as_ptr(),+ )+ };+ assert_eq!(result, 0, "libsodium seal failed");+ ciphertext+}++fn libsodium_open(ciphertext: &[u8], pk: &[u8], sk: &[u8]) -> Option<Vec<u8>> {+ if ciphertext.len() < SEAL_BYTES {+ return None;+ }+ let mut plaintext = vec![0u8; ciphertext.len() - SEAL_BYTES];+ let result = unsafe {+ sodium::crypto_box_seal_open(+ plaintext.as_mut_ptr(),+ ciphertext.as_ptr(),+ ciphertext.len() as u64,+ pk.as_ptr(),+ sk.as_ptr(),+ )+ };+ if result == 0 {+ Some(plaintext)+ } else {+ None+ }+}++fn test_keypair_generation() -> bool {+ // Generate keypair with core+ let (core_pk, core_sk) = crypto::keys::generate_keypair().unwrap();++ // Test that core keypair works with libsodium+ let plaintext = b"Keypair test";+ let sealed = libsodium_seal(plaintext, &core_pk);+ let opened = libsodium_open(&sealed, &core_pk, &core_sk);++ opened == Some(plaintext.to_vec())+}++fn test_core_to_libsodium() -> bool {+ let (pk, sk) = libsodium_keypair();+ let plaintext = b"Core to libsodium sealed box";++ let sealed = crypto::sealed::seal(plaintext, &pk).unwrap();+ let opened = libsodium_open(&sealed, &pk, &sk);++ opened == Some(plaintext.to_vec())+}++fn test_libsodium_to_core() -> bool {+ let (pk, sk) = crypto::keys::generate_keypair().unwrap();+ let plaintext = b"Libsodium to core sealed box";++ let sealed = libsodium_seal(plaintext, &pk);+ let opened = crypto::sealed::open(&sealed, &pk, &sk);++ opened.ok() == Some(plaintext.to_vec())+}++fn test_empty_plaintext() -> bool {+ let (pk, sk) = crypto::keys::generate_keypair().unwrap();+ let plaintext = b"";++ // Core seal, libsodium open+ let sealed1 = crypto::sealed::seal(plaintext, &pk).unwrap();+ let opened1 = libsodium_open(&sealed1, &pk, &sk);++ // Libsodium seal, core open+ let sealed2 = libsodium_seal(plaintext, &pk);+ let opened2 = crypto::sealed::open(&sealed2, &pk, &sk);++ opened1 == Some(vec![]) && opened2.ok() == Some(vec![])+}++fn test_large_plaintext() -> bool {+ let (pk, sk) = crypto::keys::generate_keypair().unwrap();+ let plaintext = crate::random_bytes(1024 * 1024); // 1MB++ // Core seal, libsodium open+ let sealed = crypto::sealed::seal(&plaintext, &pk).unwrap();+ let opened = libsodium_open(&sealed, &pk, &sk);++ if opened != Some(plaintext.clone()) {+ return false;+ }++ // Libsodium seal, core open+ let sealed = libsodium_seal(&plaintext, &pk);+ let opened = crypto::sealed::open(&sealed, &pk, &sk);++ opened.ok() == Some(plaintext)+}++fn test_random_data() -> bool {+ for _ in 0..50 {+ let (pk, sk) = crypto::keys::generate_keypair().unwrap();+ let plaintext = crate::random_bytes(rand::random::<usize>() % 1000 + 1);++ // Core seal, libsodium open+ let sealed = crypto::sealed::seal(&plaintext, &pk).unwrap();+ if libsodium_open(&sealed, &pk, &sk) != Some(plaintext.clone()) {+ return false;+ }++ // Libsodium seal, core open+ let sealed = libsodium_seal(&plaintext, &pk);+ if crypto::sealed::open(&sealed, &pk, &sk).ok() != Some(plaintext) {+ return false;+ }+ }+ true+}++fn test_wrong_key() -> bool {+ let (pk1, _sk1) = crypto::keys::generate_keypair().unwrap();+ let (_pk2, sk2) = crypto::keys::generate_keypair().unwrap();+ let plaintext = b"Wrong key test";++ let sealed = crypto::sealed::seal(plaintext, &pk1).unwrap();++ // Should fail with wrong secret key+ let result1 = libsodium_open(&sealed, &pk1, &sk2);+ let result2 = crypto::sealed::open(&sealed, &pk1, &sk2);++ result1.is_none() && result2.is_err()+}diff --git a/rust/validation/src/tests/secretbox.rs b/rust/validation/src/tests/secretbox.rsnew file mode 100644index 0000000000..e70e64a058--- /dev/null+++ b/rust/validation/src/tests/secretbox.rs@@ -0,0 +1,191 @@+//! SecretBox (XSalsa20-Poly1305) validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;++const KEY_BYTES: usize = 32;+const NONCE_BYTES: usize = 24;+const MAC_BYTES: usize = 16;++pub fn run_all() -> TestResult {+ println!("\nββ SecretBox (XSalsa20-Poly1305) ββ");+ run_tests! {+ "Encrypt then decrypt (roundtrip)" => test_roundtrip(),+ "Core encrypt, libsodium decrypt" => test_core_to_libsodium(),+ "Libsodium encrypt, core decrypt" => test_libsodium_to_core(),+ "Ciphertext format matches" => test_ciphertext_format(),+ "Empty plaintext" => test_empty_plaintext(),+ "Large plaintext (1MB)" => test_large_plaintext(),+ "Random data (100 iterations)" => test_random_data(),+ "Tampered ciphertext fails" => test_tampered_ciphertext(),+ }+}++fn libsodium_encrypt(plaintext: &[u8], nonce: &[u8], key: &[u8]) -> Vec<u8> {+ let mut ciphertext = vec![0u8; plaintext.len() + MAC_BYTES];+ let result = unsafe {+ sodium::crypto_secretbox_easy(+ ciphertext.as_mut_ptr(),+ plaintext.as_ptr(),+ plaintext.len() as u64,+ nonce.as_ptr(),+ key.as_ptr(),+ )+ };+ assert_eq!(result, 0, "libsodium encrypt failed");+ ciphertext+}++fn libsodium_decrypt(ciphertext: &[u8], nonce: &[u8], key: &[u8]) -> Option<Vec<u8>> {+ if ciphertext.len() < MAC_BYTES {+ return None;+ }+ let mut plaintext = vec![0u8; ciphertext.len() - MAC_BYTES];+ let result = unsafe {+ sodium::crypto_secretbox_open_easy(+ plaintext.as_mut_ptr(),+ ciphertext.as_ptr(),+ ciphertext.len() as u64,+ nonce.as_ptr(),+ key.as_ptr(),+ )+ };+ if result == 0 {+ Some(plaintext)+ } else {+ None+ }+}++fn test_roundtrip() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = b"Hello, World!";++ let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();+ let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key).unwrap();++ plaintext.to_vec() == decrypted+}++fn test_core_to_libsodium() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = b"Core to libsodium test";++ let ciphertext = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();+ let decrypted = libsodium_decrypt(&ciphertext, &nonce, &key);++ decrypted == Some(plaintext.to_vec())+}++fn test_libsodium_to_core() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = b"Libsodium to core test";++ let ciphertext = libsodium_encrypt(plaintext, &nonce, &key);+ let decrypted = crypto::secretbox::decrypt(&ciphertext, &nonce, &key);++ decrypted.ok() == Some(plaintext.to_vec())+}++fn test_ciphertext_format() -> bool {+ let key = vec![0u8; KEY_BYTES];+ let nonce = vec![0u8; NONCE_BYTES];+ let plaintext = b"Format test";++ let core_ct = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();+ let libsodium_ct = libsodium_encrypt(plaintext, &nonce, &key);++ // Debug output+ if core_ct != libsodium_ct {+ eprintln!(+ " Core ({} bytes): {:02x?}",+ core_ct.len(),+ &core_ct[..core_ct.len().min(32)]+ );+ eprintln!(+ " Libsodium({} bytes): {:02x?}",+ libsodium_ct.len(),+ &libsodium_ct[..libsodium_ct.len().min(32)]+ );+ }++ // Both should produce identical ciphertext+ core_ct == libsodium_ct+}++fn test_empty_plaintext() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = b"";++ let core_ct = crypto::secretbox::encrypt_with_nonce(plaintext, &nonce, &key).unwrap();+ let libsodium_ct = libsodium_encrypt(plaintext, &nonce, &key);++ if core_ct != libsodium_ct {+ return false;+ }++ // Both should decrypt correctly+ let core_dec = crypto::secretbox::decrypt(&core_ct, &nonce, &key).unwrap();+ let libsodium_dec = libsodium_decrypt(&libsodium_ct, &nonce, &key).unwrap();++ core_dec.is_empty() && libsodium_dec.is_empty()+}++fn test_large_plaintext() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = crate::random_bytes(1024 * 1024); // 1MB++ let core_ct = crypto::secretbox::encrypt_with_nonce(&plaintext, &nonce, &key).unwrap();+ let libsodium_ct = libsodium_encrypt(&plaintext, &nonce, &key);++ // Ciphertext should match+ if core_ct != libsodium_ct {+ return false;+ }++ // Cross-decrypt should work+ let dec1 = libsodium_decrypt(&core_ct, &nonce, &key).unwrap();+ let dec2 = crypto::secretbox::decrypt(&libsodium_ct, &nonce, &key).unwrap();++ dec1 == plaintext && dec2 == plaintext+}++fn test_random_data() -> bool {+ for _ in 0..100 {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = crate::random_bytes(rand::random::<usize>() % 1000 + 1);++ let core_ct = crypto::secretbox::encrypt_with_nonce(&plaintext, &nonce, &key).unwrap();+ let libsodium_ct = libsodium_encrypt(&plaintext, &nonce, &key);++ if core_ct != libsodium_ct {+ return false;+ }+ }+ true+}++fn test_tampered_ciphertext() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let nonce = crate::random_bytes(NONCE_BYTES);+ let plaintext = b"Tamper test";++ let mut ciphertext = libsodium_encrypt(plaintext, &nonce, &key);++ // Tamper with ciphertext+ ciphertext[0] ^= 0xff;++ // Both should fail to decrypt+ let core_result = crypto::secretbox::decrypt(&ciphertext, &nonce, &key);+ let libsodium_result = libsodium_decrypt(&ciphertext, &nonce, &key);++ core_result.is_err() && libsodium_result.is_none()+}diff --git a/rust/validation/src/tests/stream.rs b/rust/validation/src/tests/stream.rsnew file mode 100644index 0000000000..2bccbc77f2--- /dev/null+++ b/rust/validation/src/tests/stream.rs@@ -0,0 +1,336 @@+//! Stream encryption (XChaCha20-Poly1305 secretstream) validation tests++use super::TestResult;+use crate::run_tests;+use ente_core::crypto;+use libsodium_sys as sodium;++const KEY_BYTES: usize = 32;+const HEADER_BYTES: usize = 24;+const TAG_MESSAGE: u8 = 0;+const TAG_PUSH: u8 = 1;+const TAG_REKEY: u8 = 2;+const TAG_FINAL: u8 = 3;++#[allow(dead_code)]+struct LibsodiumEncryptor {+ state: sodium::crypto_secretstream_xchacha20poly1305_state,+ header: Vec<u8>,+}++impl LibsodiumEncryptor {+ fn new(key: &[u8]) -> Self {+ let mut state = sodium::crypto_secretstream_xchacha20poly1305_state {+ k: [0u8; 32],+ nonce: [0u8; 12],+ _pad: [0u8; 8],+ };+ let mut header = vec![0u8; HEADER_BYTES];+ unsafe {+ sodium::crypto_secretstream_xchacha20poly1305_init_push(+ &mut state,+ header.as_mut_ptr(),+ key.as_ptr(),+ );+ }+ Self { state, header }+ }++ fn push(&mut self, plaintext: &[u8], tag: u8) -> Vec<u8> {+ let mut ciphertext = vec![0u8; plaintext.len() + 17];+ unsafe {+ sodium::crypto_secretstream_xchacha20poly1305_push(+ &mut self.state,+ ciphertext.as_mut_ptr(),+ std::ptr::null_mut(),+ plaintext.as_ptr(),+ plaintext.len() as u64,+ std::ptr::null(),+ 0,+ tag,+ );+ }+ ciphertext+ }+}++struct LibsodiumDecryptor {+ state: sodium::crypto_secretstream_xchacha20poly1305_state,+}++impl LibsodiumDecryptor {+ fn new(key: &[u8], header: &[u8]) -> Option<Self> {+ let mut state = sodium::crypto_secretstream_xchacha20poly1305_state {+ k: [0u8; 32],+ nonce: [0u8; 12],+ _pad: [0u8; 8],+ };+ let result = unsafe {+ sodium::crypto_secretstream_xchacha20poly1305_init_pull(+ &mut state,+ header.as_ptr(),+ key.as_ptr(),+ )+ };+ if result == 0 {+ Some(Self { state })+ } else {+ None+ }+ }++ fn pull(&mut self, ciphertext: &[u8]) -> Option<(Vec<u8>, u8)> {+ if ciphertext.len() < 17 {+ return None;+ }+ let mut plaintext = vec![0u8; ciphertext.len() - 17];+ let mut tag: u8 = 0;+ let result = unsafe {+ sodium::crypto_secretstream_xchacha20poly1305_pull(+ &mut self.state,+ plaintext.as_mut_ptr(),+ std::ptr::null_mut(),+ &mut tag,+ ciphertext.as_ptr(),+ ciphertext.len() as u64,+ std::ptr::null(),+ 0,+ )+ };+ if result == 0 {+ Some((plaintext, tag))+ } else {+ None+ }+ }+}++pub fn run_all() -> TestResult {+ println!("\nββ Stream Encryption (XChaCha20-Poly1305) ββ");+ run_tests! {+ "Single chunk roundtrip (core-only)" => test_single_chunk(),+ "Multi-chunk roundtrip (core-only)" => test_multi_chunk(),+ "Core encrypt, libsodium decrypt" => test_core_to_libsodium(),+ "Libsodium encrypt, core decrypt" => test_libsodium_to_core(),+ "Libsodium TAG_PUSH interop" => test_libsodium_push_tag(),+ "Libsodium TAG_REKEY interop" => test_libsodium_rekey_tag(),+ "Multi-chunk interop" => test_multi_chunk_interop(),+ "Empty plaintext interop" => test_empty_interop(),+ "Large plaintext interop (64KB)" => test_large_interop(),+ }+}++fn test_single_chunk() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let plaintext = b"Single chunk test";++ let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let ciphertext = encryptor.push(plaintext, false).unwrap();++ let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();+ let (decrypted, tag) = decryptor.pull(&ciphertext).unwrap();++ decrypted == plaintext && tag == TAG_MESSAGE+}++fn test_multi_chunk() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let chunks = [b"First".to_vec(), b"Second".to_vec(), b"Third".to_vec()];++ let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let mut encrypted_chunks = Vec::new();++ for (i, chunk) in chunks.iter().enumerate() {+ let is_final = i == chunks.len() - 1;+ encrypted_chunks.push(encryptor.push(chunk, is_final).unwrap());+ }++ let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();++ for (i, (encrypted, original)) in encrypted_chunks.iter().zip(chunks.iter()).enumerate() {+ let (decrypted, tag) = decryptor.pull(encrypted).unwrap();+ if decrypted != *original {+ return false;+ }+ let expected_tag = if i == chunks.len() - 1 {+ TAG_FINAL+ } else {+ TAG_MESSAGE+ };+ if tag != expected_tag {+ return false;+ }+ }++ true+}++fn test_core_to_libsodium() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let plaintext = b"Core to libsodium stream test";++ // Encrypt with core+ let mut encryptor = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let ciphertext = encryptor.push(plaintext, true).unwrap();++ // Decrypt with libsodium+ let mut decryptor = LibsodiumDecryptor::new(&key, &encryptor.header).unwrap();+ let (decrypted, tag) = decryptor.pull(&ciphertext).unwrap();++ decrypted == plaintext && tag == TAG_FINAL+}++fn test_libsodium_to_core() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let plaintext = b"Libsodium to core stream test";++ // Encrypt with libsodium+ let mut encryptor = LibsodiumEncryptor::new(&key);+ let ciphertext = encryptor.push(plaintext, TAG_FINAL);++ // Decrypt with core+ let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();+ let (decrypted, tag) = decryptor.pull(&ciphertext).unwrap();++ decrypted == plaintext && tag == TAG_FINAL+}++fn test_libsodium_push_tag() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let chunks = [b"Push tag chunk".to_vec(), b"Final chunk".to_vec()];++ // Encrypt with libsodium using TAG_PUSH then TAG_FINAL+ let mut encryptor = LibsodiumEncryptor::new(&key);+ let ct_push = encryptor.push(&chunks[0], TAG_PUSH);+ let ct_final = encryptor.push(&chunks[1], TAG_FINAL);++ // Decrypt with core and verify tags+ let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();+ let (pt_push, tag_push) = decryptor.pull(&ct_push).unwrap();+ let (pt_final, tag_final) = decryptor.pull(&ct_final).unwrap();++ pt_push == chunks[0] && tag_push == TAG_PUSH && pt_final == chunks[1] && tag_final == TAG_FINAL+}++fn test_libsodium_rekey_tag() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let chunks = [b"Rekey chunk".to_vec(), b"After rekey".to_vec()];++ // Encrypt with libsodium using TAG_REKEY then TAG_FINAL+ let mut encryptor = LibsodiumEncryptor::new(&key);+ let ct_rekey = encryptor.push(&chunks[0], TAG_REKEY);+ let ct_final = encryptor.push(&chunks[1], TAG_FINAL);++ // Decrypt with core and verify tags+ let mut decryptor = crypto::stream::StreamDecryptor::new(&encryptor.header, &key).unwrap();+ let (pt_rekey, tag_rekey) = decryptor.pull(&ct_rekey).unwrap();+ let (pt_final, tag_final) = decryptor.pull(&ct_final).unwrap();++ pt_rekey == chunks[0]+ && tag_rekey == TAG_REKEY+ && pt_final == chunks[1]+ && tag_final == TAG_FINAL+}++fn test_multi_chunk_interop() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let chunks = [b"Alpha".to_vec(), b"Beta".to_vec(), b"Gamma".to_vec()];++ // Core encrypt, libsodium decrypt+ let mut core_enc = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let mut encrypted = Vec::new();+ for (i, chunk) in chunks.iter().enumerate() {+ let is_final = i == chunks.len() - 1;+ encrypted.push(core_enc.push(chunk, is_final).unwrap());+ }++ let mut ls_dec = LibsodiumDecryptor::new(&key, &core_enc.header).unwrap();+ for (i, (ct, original)) in encrypted.iter().zip(chunks.iter()).enumerate() {+ let (pt, tag) = ls_dec.pull(ct).unwrap();+ if pt != *original {+ return false;+ }+ let expected = if i == chunks.len() - 1 {+ TAG_FINAL+ } else {+ TAG_MESSAGE+ };+ if tag != expected {+ return false;+ }+ }++ // Libsodium encrypt, core decrypt+ let mut ls_enc = LibsodiumEncryptor::new(&key);+ let mut encrypted = Vec::new();+ for (i, chunk) in chunks.iter().enumerate() {+ let tag = if i == chunks.len() - 1 {+ TAG_FINAL+ } else {+ TAG_MESSAGE+ };+ encrypted.push(ls_enc.push(chunk, tag));+ }++ let mut core_dec = crypto::stream::StreamDecryptor::new(&ls_enc.header, &key).unwrap();+ for (i, (ct, original)) in encrypted.iter().zip(chunks.iter()).enumerate() {+ let (pt, tag) = core_dec.pull(ct).unwrap();+ if pt != *original {+ return false;+ }+ let expected = if i == chunks.len() - 1 {+ TAG_FINAL+ } else {+ TAG_MESSAGE+ };+ if tag != expected {+ return false;+ }+ }++ true+}++fn test_empty_interop() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let plaintext = b"";++ // Core encrypt, libsodium decrypt+ let mut core_enc = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let ct = core_enc.push(plaintext, true).unwrap();+ let mut ls_dec = LibsodiumDecryptor::new(&key, &core_enc.header).unwrap();+ let (pt, tag) = ls_dec.pull(&ct).unwrap();+ if pt != plaintext || tag != TAG_FINAL {+ return false;+ }++ // Libsodium encrypt, core decrypt+ let mut ls_enc = LibsodiumEncryptor::new(&key);+ let ct = ls_enc.push(plaintext, TAG_FINAL);+ let mut core_dec = crypto::stream::StreamDecryptor::new(&ls_enc.header, &key).unwrap();+ let (pt, tag) = core_dec.pull(&ct).unwrap();++ pt == plaintext && tag == TAG_FINAL+}++fn test_large_interop() -> bool {+ let key = crate::random_bytes(KEY_BYTES);+ let plaintext = crate::random_bytes(65536);++ // Core encrypt, libsodium decrypt+ let mut core_enc = crypto::stream::StreamEncryptor::new(&key).unwrap();+ let ct = core_enc.push(&plaintext, true).unwrap();+ let mut ls_dec = LibsodiumDecryptor::new(&key, &core_enc.header).unwrap();+ let (pt, tag) = ls_dec.pull(&ct).unwrap();+ if pt != plaintext || tag != TAG_FINAL {+ return false;+ }++ // Libsodium encrypt, core decrypt+ let mut ls_enc = LibsodiumEncryptor::new(&key);+ let ct = ls_enc.push(&plaintext, TAG_FINAL);+ let mut core_dec = crypto::stream::StreamDecryptor::new(&ls_enc.header, &key).unwrap();+ let (pt, tag) = core_dec.pull(&ct).unwrap();++ pt == plaintext && tag == TAG_FINAL+}