padding_admission.rs (1831B)
1 use radroots_simplex_smp_crypto::prelude::{ 2 RadrootsSimplexSmpCryptoError, decrypt_padded, encrypt_padded, 3 }; 4 5 const KEY: [u8; 32] = [7; 32]; 6 const NONCE: [u8; 24] = [9; 24]; 7 8 #[test] 9 fn accepted_payloads_round_trip_without_losing_bytes() { 10 for length in [0_usize, 1, 4096, usize::from(u16::MAX)] { 11 let plaintext: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect(); 12 for extra_padding in [0, 3] { 13 let ciphertext = encrypt_padded(&KEY, &NONCE, &plaintext, length + 2 + extra_padding) 14 .expect("representable plaintext must fit the padded message"); 15 assert_eq!( 16 decrypt_padded(&KEY, &NONCE, &ciphertext).unwrap(), 17 plaintext, 18 "accepted plaintext must preserve every byte" 19 ); 20 } 21 } 22 } 23 24 #[test] 25 fn unrepresentable_payload_lengths_are_rejected() { 26 for length in [usize::from(u16::MAX) + 1, usize::from(u16::MAX) + 2] { 27 let plaintext = vec![0xa5; length]; 28 let result = encrypt_padded(&KEY, &NONCE, &plaintext, length + 2); 29 if let Ok(ciphertext) = &result { 30 let decoded = decrypt_padded(&KEY, &NONCE, ciphertext).unwrap(); 31 assert_eq!( 32 decoded.len(), 33 plaintext.len(), 34 "an accepted encoding must never lose plaintext bytes" 35 ); 36 } 37 assert!(matches!( 38 result, 39 Err(RadrootsSimplexSmpCryptoError::InvalidMessageLength { actual, .. }) 40 if actual == length 41 )); 42 } 43 } 44 45 #[test] 46 fn insufficient_padding_capacity_is_rejected() { 47 assert!(matches!( 48 encrypt_padded(&KEY, &NONCE, b"abc", 4), 49 Err(RadrootsSimplexSmpCryptoError::InvalidMessageLength { 50 actual: 3, 51 padded: 4 52 }) 53 )); 54 }