1use std::cmp::Ordering;
109use std::convert::TryFrom;
110use std::num::{NonZeroU16, NonZeroUsize};
111use std::sync::Mutex;
112
113use rand::TryRng;
114use subtle_ng::{Choice, ConditionallySelectable, ConstantTimeEq};
115use vitaminc_context::Context;
116use vitaminc_ore::{OrderPlaintext, OrderTarget};
117use vitaminc_protected::{Controlled, Protected};
118use vitaminc_random::SafeRand;
119use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
120
121#[cfg(test)]
122use crate::ciphertext::ParseError;
123use crate::ciphertext::{parse_header, WireHeader, WIRE_HEADER_LEN};
124use crate::primitives::cmac::{final_block, prefix_block, Branch, CmacAccumulator, WIDTH_BIT6};
125use crate::primitives::hash::FixedPiZ2Hash;
126use crate::primitives::prp::LemireFyPrp;
127use crate::primitives::{stack, AesBlock, Hash, HashKey, Prp};
128use crate::scheme::decompose::{num_blocks_6bit, Blocks6};
129use crate::scheme::keys;
130use crate::scheme::width::FirstDiff;
131use crate::{OreError, OreScheme, Query, Term};
132
133const VERSION: u8 = 0x02;
134pub(crate) const SCHEME_ID: u8 = 0x03;
135const WIRE: WireHeader = WireHeader {
137 version: VERSION,
138 scheme_id: SCHEME_ID,
139};
140const DOMAIN: usize = 64;
141const STREAM_BLOCKS: usize = 32;
143const F_LEN: usize = 16;
144const RIGHT_LEN: usize = DOMAIN / 8; const PADDING_LEN: usize = 3;
148const HEADER_LEN: usize = WIRE_HEADER_LEN + PADDING_LEN;
149const NONCE_LEN: usize = 16;
150
151const ROOT_LABEL: [u8; 16] = *b"ORE.v2.chainroot";
155const _: () = assert!(
156 ROOT_LABEL[15] > 14,
157 "root label collides with a legacy PRF input"
158);
159const ACC_KEY_LABEL: [u8; 16] = *b"ORE.v2.chain.acc";
161
162#[inline]
164fn total_len(count: usize) -> usize {
165 HEADER_LEN + count + count * F_LEN + NONCE_LEN + count * RIGHT_LEN
166}
167
168#[inline]
171fn left_len(count: usize) -> usize {
172 HEADER_LEN + count + count * F_LEN
173}
174
175#[inline]
177fn xt_at(s: &[u8], i: usize) -> u8 {
178 s[HEADER_LEN + i]
179}
180#[inline]
181fn f_at(s: &[u8], count: usize, i: usize) -> &[u8] {
182 let o = HEADER_LEN + count + i * F_LEN;
183 &s[o..o + F_LEN]
184}
185#[inline]
186fn nonce_at(s: &[u8], count: usize) -> &[u8] {
187 let o = HEADER_LEN + count + count * F_LEN;
188 &s[o..o + NONCE_LEN]
189}
190#[inline]
191fn right_at(s: &[u8], count: usize, i: usize) -> &[u8] {
192 let o = HEADER_LEN + count + count * F_LEN + NONCE_LEN + i * RIGHT_LEN;
193 &s[o..o + RIGHT_LEN]
194}
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum Padding {
213 None,
215 PowerOfTwo {
236 min_bytes: u16,
238 },
239 Fixed {
243 max_bytes: NonZeroU16,
246 },
247}
248
249impl Default for Padding {
250 fn default() -> Self {
252 Padding::PowerOfTwo { min_bytes: 16 }
253 }
254}
255
256impl Padding {
257 pub fn padded_len(self, len: usize) -> Result<usize, OreError> {
263 let padded = match self {
264 Padding::None => len,
265 Padding::PowerOfTwo { min_bytes } if len <= min_bytes.into() => min_bytes.into(),
266 Padding::PowerOfTwo { .. } => len
267 .checked_next_power_of_two()
268 .ok_or(OreError::TooManyBlocks)?,
269 Padding::Fixed { max_bytes } if len <= max_bytes.get().into() => max_bytes.get().into(),
270 Padding::Fixed { .. } => return Err(OreError::ExceedsPadding),
271 };
272 if padded > MAX_STR_BYTES {
273 return Err(OreError::TooManyBlocks);
274 }
275 Ok(padded)
276 }
277
278 fn to_wire(self) -> [u8; PADDING_LEN] {
280 let (kind, n) = match self {
281 Padding::None => (0, 0),
282 Padding::PowerOfTwo { min_bytes } => (1, min_bytes),
283 Padding::Fixed { max_bytes } => (2, max_bytes.get()),
284 };
285 let [hi, lo] = n.to_be_bytes();
286 [kind, hi, lo]
287 }
288
289 fn from_wire(tag: [u8; PADDING_LEN]) -> Option<Self> {
292 let [kind, hi, lo] = tag;
293 let n = u16::from_be_bytes([hi, lo]);
294 let padding = match kind {
295 0 if n == 0 => Padding::None,
296 1 => Padding::PowerOfTwo { min_bytes: n },
297 2 => Padding::Fixed {
298 max_bytes: NonZeroU16::new(n)?,
299 },
300 _ => return None,
301 };
302 padding.padded_len(0).ok().map(|_| padding)
303 }
304
305 fn admits_count(self, count: usize) -> bool {
310 match self {
311 Padding::None => true,
312 Padding::Fixed { max_bytes } => count == num_blocks_6bit(max_bytes.get().into()),
313 Padding::PowerOfTwo { min_bytes } => {
314 let min_bytes = usize::from(min_bytes);
315 count == num_blocks_6bit(min_bytes)
316 || (0..=MAX_STR_BYTES.ilog2()).any(|k| {
317 let bucket = 1usize << k;
318 bucket > min_bytes && count == num_blocks_6bit(bucket)
319 })
320 }
321 }
322 }
323}
324
325pub const DEFAULT_MAX_STR_BYTES: NonZeroUsize = match NonZeroUsize::new(1024) {
329 Some(n) => n,
330 None => NonZeroUsize::MIN,
331};
332
333#[derive(Clone, Debug, PartialEq, Eq)]
358pub struct Options {
359 salt: Vec<u8>,
360 padding: Padding,
361 max_bytes: NonZeroUsize,
362}
363
364impl Default for Options {
365 fn default() -> Self {
367 Self {
368 salt: Vec::new(),
369 padding: Padding::default(),
370 max_bytes: DEFAULT_MAX_STR_BYTES,
371 }
372 }
373}
374
375impl Options {
376 pub fn new() -> Self {
378 Self::default()
379 }
380
381 pub fn with_salt(self, salt: &Context<'_>) -> Self {
389 Self {
390 salt: salt.as_bytes().to_vec(),
391 ..self
392 }
393 }
394
395 pub fn with_padding(self, padding: Padding) -> Self {
397 Self { padding, ..self }
398 }
399
400 pub fn with_max_bytes(self, max_bytes: NonZeroUsize) -> Self {
407 Self { max_bytes, ..self }
408 }
409
410 pub fn salt(&self) -> &[u8] {
412 &self.salt
413 }
414
415 pub fn padding(&self) -> Padding {
417 self.padding
418 }
419
420 pub fn max_bytes(&self) -> NonZeroUsize {
422 self.ceiling()
423 }
424
425 fn ceiling(&self) -> NonZeroUsize {
427 match self.padding {
428 Padding::Fixed { max_bytes } => self.max_bytes.min(NonZeroUsize::from(max_bytes)),
429 _ => self.max_bytes,
430 }
431 }
432
433 fn check(&self) -> Result<(), OreError> {
435 self.padding
437 .padded_len(0)
438 .map_err(|_| OreError::InitFailed)?;
439 self.padding
440 .padded_len(self.ceiling().get())
441 .map_err(|_| OreError::InitFailed)?;
442 Ok(())
443 }
444}
445
446#[derive(Clone, Debug)]
449pub(crate) struct VarLeft {
450 xt: Vec<u8>,
451 f: Vec<[u8; F_LEN]>,
452 padding: Padding,
453}
454
455#[derive(Clone, Debug)]
457pub(crate) struct VarRight {
458 nonce: [u8; NONCE_LEN],
459 blocks: Vec<[u8; RIGHT_LEN]>,
460}
461
462#[derive(Clone, Debug)]
465pub(crate) struct VarCipherText {
466 left: VarLeft,
467 right: VarRight,
468}
469
470impl VarLeft {
471 pub fn to_bytes(&self) -> Vec<u8> {
473 let count = self.xt.len();
474 let mut out = Vec::with_capacity(left_len(count));
475 write_header(count, self.padding, &mut out);
476 out.extend_from_slice(&self.xt);
477 for fb in &self.f {
478 out.extend_from_slice(fb);
479 }
480 out
481 }
482
483 #[cfg(test)]
485 pub fn padding(&self) -> Padding {
486 self.padding
487 }
488}
489
490#[cfg(test)]
493fn parse_left_view(data: &[u8], count: usize, padding: Padding) -> VarLeft {
494 let xt = data[HEADER_LEN..HEADER_LEN + count].to_vec();
495 let mut f = Vec::with_capacity(count);
496 for n in 0..count {
497 let mut fb = [0u8; F_LEN];
498 fb.copy_from_slice(f_at(data, count, n));
499 f.push(fb);
500 }
501 VarLeft { xt, f, padding }
502}
503
504impl VarCipherText {
505 pub fn to_bytes(&self) -> Vec<u8> {
507 let count = self.left.xt.len();
508 let mut out = Vec::with_capacity(total_len(count));
509 write_header(count, self.left.padding, &mut out);
510 out.extend_from_slice(&self.left.xt);
511 for fb in &self.left.f {
512 out.extend_from_slice(fb);
513 }
514 out.extend_from_slice(&self.right.nonce);
515 for rb in &self.right.blocks {
516 out.extend_from_slice(rb);
517 }
518 out
519 }
520
521 #[cfg(test)]
523 pub fn padding(&self) -> Padding {
524 self.left.padding
525 }
526
527 #[cfg(test)]
529 pub fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
530 let (count, padding) = parse_chained_header(data).ok_or(ParseError)?;
531 if data.len() != total_len(count) {
532 return Err(ParseError);
533 }
534 if !symbols_in_domain(data, count) {
537 return Err(ParseError);
538 }
539 let left = parse_left_view(data, count, padding);
540 let mut nonce = [0u8; NONCE_LEN];
541 nonce.copy_from_slice(nonce_at(data, count));
542 let mut blocks = Vec::with_capacity(count);
543 for n in 0..count {
544 let mut rb = [0u8; RIGHT_LEN];
545 rb.copy_from_slice(right_at(data, count, n));
546 blocks.push(rb);
547 }
548 Ok(VarCipherText {
549 left,
550 right: VarRight { nonce, blocks },
551 })
552 }
553}
554
555fn write_header(count: usize, padding: Padding, out: &mut Vec<u8>) {
562 WIRE.write(u16::try_from(count).unwrap_or(u16::MAX), out);
563 out.extend_from_slice(&padding.to_wire());
564}
565
566fn parse_chained_header(view: &[u8]) -> Option<(usize, Padding)> {
569 let ((ver, sid, count), body) = parse_header(view).ok()?;
570 if ver != VERSION || sid != SCHEME_ID {
571 return None;
572 }
573 let tag = <[u8; PADDING_LEN]>::try_from(body.get(..PADDING_LEN)?).ok()?;
574 let padding = Padding::from_wire(tag)?;
575 padding.admits_count(count).then_some((count, padding))
576}
577
578fn parse_pair(a: &[u8], b: &[u8]) -> Option<(usize, usize)> {
582 let (ca, pa) = parse_chained_header(a)?;
583 let (cb, pb) = parse_chained_header(b)?;
584 (pa == pb).then_some((ca, cb))
585}
586
587pub struct OreAes128Bit6Chained {
592 k_acc: [u8; 16],
594 options: Options,
597 rng: Mutex<SafeRand>,
598}
599
600impl std::fmt::Debug for OreAes128Bit6Chained {
602 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
603 f.debug_struct("OreAes128Bit6Chained")
604 .field("options", &self.options)
605 .finish_non_exhaustive()
606 }
607}
608
609impl OreAes128Bit6Chained {
610 pub fn init(key: Protected<[u8; 16]>) -> Result<Self, OreError> {
614 Self::init_with(key, Options::default())
615 }
616
617 pub fn init_with_salt(key: Protected<[u8; 16]>, salt: &Context<'_>) -> Result<Self, OreError> {
621 Self::init_with(key, Options::default().with_salt(salt))
622 }
623
624 pub fn init_with(key: Protected<[u8; 16]>, options: Options) -> Result<Self, OreError> {
646 Self::init_with_rng(key, options, SafeRand::from_entropy()?)
647 }
648
649 #[cfg(any(test, feature = "test-support"))]
653 pub fn init_seeded(
654 key: Protected<[u8; 16]>,
655 options: Options,
656 seed: [u8; 32],
657 ) -> Result<Self, OreError> {
658 use vitaminc_random::SeedableRng;
659 Self::init_with_rng(key, options, SafeRand::from_seed(seed))
660 }
661
662 fn init_with_rng(
663 key: Protected<[u8; 16]>,
664 options: Options,
665 rng: SafeRand,
666 ) -> Result<Self, OreError> {
667 options.check()?;
668 let k_salt = keys::salted(&keys::root(key.risky_ref(), &ROOT_LABEL), options.salt());
669 let k_acc = *keys::subkey(&k_salt, &ACC_KEY_LABEL);
670 Ok(Self {
671 k_acc,
672 options,
673 rng: Mutex::new(rng),
674 })
675 }
676
677 fn fill_nonce(&self, nonce: &mut [u8; NONCE_LEN]) {
679 let mut rng = self
680 .rng
681 .lock()
682 .unwrap_or_else(|poisoned| poisoned.into_inner());
683 match rng.try_fill_bytes(nonce) {
684 Ok(()) => {}
685 Err(never) => match never {},
686 }
687 }
688
689 pub fn options(&self) -> &Options {
691 &self.options
692 }
693
694 pub fn padding(&self) -> Padding {
696 self.options.padding()
697 }
698
699 fn prp_at(&self, acc: &CmacAccumulator, n: u16) -> LemireFyPrp<DOMAIN> {
701 let mut stream = [0u8; STREAM_BLOCKS * 16];
702 for (c, chunk) in stream.chunks_mut(16).enumerate() {
703 chunk.copy_from_slice(&acc.finalize(&final_block(
704 Branch::PrpStream,
705 n,
706 c as u16,
707 WIDTH_BIT6,
708 )));
709 }
710 let prp = LemireFyPrp::<DOMAIN>::from_stream(&stream);
711 stream.zeroize();
712 prp
713 }
714
715 #[cfg(test)]
721 pub(crate) fn encrypt_var(&self, x: &[u8]) -> Result<VarCipherText, OreError> {
722 stack::scrubbed(|| self.encrypt_blocks(&check_symbols(x)?, Padding::None))
723 }
724
725 fn encrypt_blocks<B: AsRef<[u8]>>(
732 &self,
733 x: &Blocks6<B>,
734 padding: Padding,
735 ) -> Result<VarCipherText, OreError> {
736 let count = x.len();
737 if count > u16::MAX as usize {
738 return Err(OreError::TooManyBlocks);
739 }
740
741 let mut acc = CmacAccumulator::new(&self.k_acc);
742 let mut nonce = [0u8; NONCE_LEN];
743 self.fill_nonce(&mut nonce);
744 let hasher = FixedPiZ2Hash::new(HashKey::from_slice(&nonce));
745
746 let mut xt = Vec::with_capacity(count);
747 let mut f = Vec::with_capacity(count);
748 let mut blocks = Vec::with_capacity(count);
749
750 let mut ro = [AesBlock::default(); DOMAIN];
754
755 for n in 0..count {
756 let sym = x.symbol(n);
757 let n16 = n as u16;
758 let prp = self.prp_at(&acc, n16);
759 let permuted = prp.permute(sym).get();
760 xt.push(permuted);
761
762 for (j, blk) in ro.iter_mut().enumerate() {
764 blk.copy_from_slice(&acc.finalize(&final_block(
765 Branch::RoKey,
766 n16,
767 j as u16,
768 WIDTH_BIT6,
769 )));
770 }
771 f.push(acc.finalize(&final_block(
775 Branch::RoKey,
776 n16,
777 permuted as u16,
778 WIDTH_BIT6,
779 )));
780
781 let mut rb = [0u8; RIGHT_LEN];
783 hasher.hash_all_into(&mut ro, &mut rb);
784 prp.indicator_mask_xor(sym, &mut rb);
785 blocks.push(rb);
786
787 acc.absorb(&prefix_block(n16, sym.get()));
788 }
789
790 for blk in ro.iter_mut() {
792 blk.as_mut_slice().zeroize();
793 }
794
795 Ok(VarCipherText {
796 left: VarLeft { xt, f, padding },
797 right: VarRight { nonce, blocks },
798 })
799 }
800
801 #[cfg(test)]
804 pub(crate) fn encrypt_left_var(&self, x: &[u8]) -> Result<VarLeft, OreError> {
805 stack::scrubbed(|| self.encrypt_left_blocks(&check_symbols(x)?, Padding::None))
806 }
807
808 fn encrypt_left_blocks<B: AsRef<[u8]>>(
811 &self,
812 x: &Blocks6<B>,
813 padding: Padding,
814 ) -> Result<VarLeft, OreError> {
815 let count = x.len();
816 if count > u16::MAX as usize {
817 return Err(OreError::TooManyBlocks);
818 }
819
820 let mut acc = CmacAccumulator::new(&self.k_acc);
821 let mut xt = Vec::with_capacity(count);
822 let mut f = Vec::with_capacity(count);
823
824 for n in 0..count {
825 let sym = x.symbol(n);
826 let n16 = n as u16;
827 let prp = self.prp_at(&acc, n16);
828 let permuted = prp.permute(sym).get();
829 xt.push(permuted);
830 f.push(acc.finalize(&final_block(
831 Branch::RoKey,
832 n16,
833 permuted as u16,
834 WIDTH_BIT6,
835 )));
836 acc.absorb(&prefix_block(n16, sym.get()));
837 }
838 Ok(VarLeft { xt, f, padding })
839 }
840
841 #[cfg(test)]
846 pub(crate) fn encrypt_str(&self, s: &str) -> Result<VarCipherText, OreError> {
847 self.encrypt_padded_bytes(s.as_bytes())
848 }
849
850 #[cfg(test)]
853 pub(crate) fn encrypt_left_str(&self, s: &str) -> Result<VarLeft, OreError> {
854 self.encrypt_left_padded_bytes(s.as_bytes())
855 }
856
857 pub(crate) fn encrypt_padded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
876 stack::scrubbed(|| {
877 self.encrypt_blocks(
878 &padded_bytes_to_blocks(bytes, &self.options)?,
879 self.padding(),
880 )
881 })
882 }
883
884 pub(crate) fn encrypt_left_padded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
886 stack::scrubbed(|| {
887 self.encrypt_left_blocks(
888 &padded_bytes_to_blocks(bytes, &self.options)?,
889 self.padding(),
890 )
891 })
892 }
893
894 pub(crate) fn encrypt_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
902 stack::scrubbed(|| self.encrypt_blocks(&bytes_to_blocks(bytes)?, Padding::None))
903 }
904
905 pub(crate) fn encrypt_left_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
907 stack::scrubbed(|| self.encrypt_left_blocks(&bytes_to_blocks(bytes)?, Padding::None))
908 }
909}
910
911impl crate::sealed::Sealed for OreAes128Bit6Chained {}
912
913enum Path {
921 Padded,
922 Unpadded,
923}
924
925impl OreAes128Bit6Chained {
926 fn path(&self, plaintext: &OrderPlaintext) -> Result<Path, OreError> {
927 match plaintext.target() {
928 OrderTarget::Bytes => {
929 if plaintext.bytes().risky_ref().len() > self.options.max_bytes().get() {
930 return Err(OreError::TooLong);
931 }
932 Ok(Path::Unpadded)
933 }
934 target if target.width().is_some() => Ok(Path::Unpadded),
935 _ => Ok(Path::Padded),
936 }
937 }
938}
939
940impl OreScheme for OreAes128Bit6Chained {
941 fn encrypt_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Term, OreError> {
945 let bytes = plaintext.bytes().risky_ref();
946 let ct = match self.path(plaintext)? {
947 Path::Padded => self.encrypt_padded_bytes(bytes)?,
948 Path::Unpadded => self.encrypt_unpadded_bytes(bytes)?,
949 };
950 Ok(Term::new(ct.to_bytes()))
951 }
952
953 fn encrypt_query_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Query, OreError> {
954 let bytes = plaintext.bytes().risky_ref();
955 let left = match self.path(plaintext)? {
956 Path::Padded => self.encrypt_left_padded_bytes(bytes)?,
957 Path::Unpadded => self.encrypt_left_unpadded_bytes(bytes)?,
958 };
959 Ok(Query::new(left.to_bytes()))
960 }
961
962 fn compare_raw_slices(a: &[u8], b: &[u8]) -> Option<Ordering> {
966 let (ca, cb) = parse_pair(a, b)?;
967 if a.len() != total_len(ca) || b.len() != total_len(cb) {
968 return None;
969 }
970 if !symbols_in_domain(a, ca) || !symbols_in_domain(b, cb) {
971 return None;
972 }
973 Some(Self::compare_views(a, ca, b, cb))
976 }
977
978 fn compare_left_to_full(left: &[u8], full: &[u8]) -> Option<Ordering> {
989 let (cl, cf) = parse_pair(left, full)?;
990 if left.len() != left_len(cl) || full.len() != total_len(cf) {
992 return None;
993 }
994 if !symbols_in_domain(left, cl) || !symbols_in_domain(full, cf) {
995 return None;
996 }
997 Some(Self::compare_views(left, cl, full, cf))
998 }
999}
1000
1001impl OreAes128Bit6Chained {
1002 fn compare_views(a: &[u8], ca: usize, b: &[u8], cb: usize) -> Ordering {
1018 let min_count = ca.min(cb);
1019 let mut is_equal = Choice::from(1u8);
1020 let mut diff = FirstDiff::<RIGHT_LEN>::new();
1021 for n in 0..min_count {
1022 let differs = !xt_at(a, n).ct_eq(&xt_at(b, n)) | !f_at(a, ca, n).ct_eq(f_at(b, cb, n));
1023 let first = is_equal & differs;
1025 diff.latch(xt_at(a, n), f_at(a, ca, n), right_at(b, cb, n), first);
1026 is_equal.conditional_assign(&Choice::from(0u8), first);
1027 }
1028
1029 if bool::from(is_equal) {
1030 return ca.cmp(&cb);
1032 }
1033
1034 let hasher = FixedPiZ2Hash::new(HashKey::from_slice(nonce_at(b, cb)));
1035 if diff.resolve(&hasher) == 1 {
1036 Ordering::Greater
1037 } else {
1038 Ordering::Less
1039 }
1040 }
1041}
1042
1043impl Drop for OreAes128Bit6Chained {
1044 fn drop(&mut self) {
1045 self.k_acc.zeroize();
1046 }
1047}
1048
1049impl ZeroizeOnDrop for OreAes128Bit6Chained {}
1051
1052fn symbols_in_domain(view: &[u8], count: usize) -> bool {
1057 (0..count).all(|i| usize::from(xt_at(view, i)) < DOMAIN)
1058}
1059
1060pub const MAX_STR_BYTES: usize = u16::MAX as usize * 6 / 8;
1063
1064const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES) <= u16::MAX as usize);
1065const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES + 1) > u16::MAX as usize);
1066
1067#[cfg(test)]
1071fn check_symbols(x: &[u8]) -> Result<Blocks6<&[u8]>, OreError> {
1072 if x.len() > u16::MAX as usize {
1073 return Err(OreError::TooManyBlocks);
1074 }
1075 Blocks6::check(x)
1076}
1077
1078#[cfg(test)]
1083fn str_to_blocks(s: &str, options: &Options) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1084 padded_bytes_to_blocks(s.as_bytes(), options)
1085}
1086
1087fn padded_bytes_to_blocks(
1090 bytes: &[u8],
1091 options: &Options,
1092) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1093 if bytes.len() > MAX_STR_BYTES {
1094 return Err(OreError::TooManyBlocks);
1095 }
1096 let padding = options.padding();
1097 let padded = padding.padded_len(bytes.len())?;
1098 if bytes.len() > options.max_bytes().get() {
1099 return Err(OreError::TooLong);
1100 }
1101 if padding != Padding::None {
1102 refuse_trailing_nul(bytes)?;
1103 }
1104 Ok(Blocks6::decompose_padded(
1105 bytes,
1106 Zeroizing::new(vec![0u8; num_blocks_6bit(padded)]),
1107 ))
1108}
1109
1110fn bytes_to_blocks(bytes: &[u8]) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
1115 if bytes.len() > MAX_STR_BYTES {
1116 return Err(OreError::TooManyBlocks);
1117 }
1118 Ok(Blocks6::decompose(
1119 bytes,
1120 Zeroizing::new(vec![0u8; num_blocks_6bit(bytes.len())]),
1121 ))
1122}
1123
1124#[inline(never)]
1136fn refuse_trailing_nul(bytes: &[u8]) -> Result<(), OreError> {
1137 if bytes.last() == Some(&0) {
1138 return Err(core::hint::black_box(OreError::TrailingNul));
1139 }
1140 Ok(())
1141}
1142
1143#[cfg(kani)]
1144mod kani_proofs {
1145 use super::*;
1146
1147 #[kani::proof]
1152 fn power_of_two_never_shrinks_and_is_idempotent() {
1153 let min_bytes: u16 = kani::any();
1154 let len: usize = kani::any();
1155 kani::assume(len <= MAX_STR_BYTES);
1156 let padding = Padding::PowerOfTwo { min_bytes };
1157 if let Ok(padded) = padding.padded_len(len) {
1158 assert!(padded >= len);
1159 assert!(padded <= MAX_STR_BYTES);
1160 assert!(padded.is_power_of_two() || padded == usize::from(min_bytes));
1161 assert!(matches!(padding.padded_len(padded), Ok(again) if again == padded));
1162 }
1163 }
1164
1165 #[kani::proof]
1168 fn power_of_two_is_monotone() {
1169 let min_bytes: u16 = kani::any();
1170 let a: usize = kani::any();
1171 let b: usize = kani::any();
1172 kani::assume(a <= b && b <= MAX_STR_BYTES);
1173 let padding = Padding::PowerOfTwo { min_bytes };
1174 if let (Ok(pa), Ok(pb)) = (padding.padded_len(a), padding.padded_len(b)) {
1175 assert!(pa <= pb);
1176 }
1177 }
1178
1179 #[kani::proof]
1182 fn fixed_pads_everything_that_fits() {
1183 let max_bytes: NonZeroU16 = kani::any();
1184 let len: usize = kani::any();
1185 kani::assume(len <= MAX_STR_BYTES);
1186 let padding = Padding::Fixed { max_bytes };
1187 let max_bytes = max_bytes.get();
1188 match padding.padded_len(len) {
1189 Ok(padded) => {
1190 assert!(len <= usize::from(max_bytes) && padded == usize::from(max_bytes))
1191 }
1192 Err(OreError::ExceedsPadding) => assert!(len > usize::from(max_bytes)),
1193 Err(OreError::TooManyBlocks) => assert!(usize::from(max_bytes) > MAX_STR_BYTES),
1194 Err(_) => assert!(false),
1195 }
1196 }
1197}
1198
1199#[cfg(test)]
1200mod compat_vectors;
1201
1202#[cfg(test)]
1203mod tests {
1204 use super::*;
1205 use crate::testing::{
1206 bytes_pt, ceiling, fixed_key, fixed_padding, i128_pt, salt, text_pt, u128_pt,
1207 };
1208
1209 fn ore() -> OreAes128Bit6Chained {
1210 OreAes128Bit6Chained::init(fixed_key(0x11)).unwrap()
1211 }
1212
1213 fn ore_with(padding: Padding) -> OreAes128Bit6Chained {
1214 OreAes128Bit6Chained::init_with(fixed_key(0x11), Options::default().with_padding(padding))
1215 .unwrap()
1216 }
1217
1218 fn ore_with_max(padding: Padding, max_bytes: usize) -> OreAes128Bit6Chained {
1220 let options = Options::default()
1221 .with_padding(padding)
1222 .with_max_bytes(ceiling(max_bytes));
1223 OreAes128Bit6Chained::init_with(fixed_key(0x11), options).unwrap()
1224 }
1225
1226 #[test]
1230 fn strings_over_the_ceiling_are_refused() {
1231 type C = OreAes128Bit6Chained;
1232 let c = ore();
1233 assert_eq!(c.options().max_bytes(), DEFAULT_MAX_STR_BYTES);
1234 assert!(c.encrypt_str(&"a".repeat(1024)).is_ok());
1235 assert!(matches!(
1236 c.encrypt_str(&"a".repeat(1025)),
1237 Err(OreError::TooLong)
1238 ));
1239 assert!(matches!(
1240 c.encrypt_left_str(&"a".repeat(1025)),
1241 Err(OreError::TooLong)
1242 ));
1243
1244 let small = C::init_with(
1245 fixed_key(0x11),
1246 Options::default().with_max_bytes(ceiling(100)),
1247 )
1248 .unwrap();
1249 assert!(small.encrypt_str(&"a".repeat(100)).is_ok());
1250 assert!(matches!(
1251 small.encrypt_str(&"a".repeat(101)),
1252 Err(OreError::TooLong)
1253 ));
1254 let unpadded = C::init_with(
1257 fixed_key(0x11),
1258 Options::default()
1259 .with_padding(Padding::None)
1260 .with_max_bytes(ceiling(8)),
1261 )
1262 .unwrap();
1263 assert!(unpadded.encrypt_str("12345678").is_ok());
1264 assert!(matches!(
1265 unpadded.encrypt_str("123456789"),
1266 Err(OreError::TooLong)
1267 ));
1268
1269 let fixed = ore_with(fixed_padding(200));
1272 assert_eq!(fixed.options().max_bytes().get(), 200);
1273 assert!(fixed.encrypt_str(&"a".repeat(200)).is_ok());
1274 assert!(matches!(
1275 fixed.encrypt_str(&"a".repeat(201)),
1276 Err(OreError::ExceedsPadding)
1277 ));
1278 let fixed_low = C::init_with(
1279 fixed_key(0x11),
1280 Options::default()
1281 .with_padding(fixed_padding(200))
1282 .with_max_bytes(ceiling(50)),
1283 )
1284 .unwrap();
1285 assert_eq!(fixed_low.options().max_bytes().get(), 50);
1286 assert!(matches!(
1287 fixed_low.encrypt_str(&"a".repeat(51)),
1288 Err(OreError::TooLong)
1289 ));
1290 assert_eq!(
1292 fixed_low.encrypt_str("abc").unwrap().to_bytes().len(),
1293 total_len(num_blocks_6bit(200))
1294 );
1295
1296 assert!(matches!(
1299 C::init_with(
1300 fixed_key(0x11),
1301 Options::default().with_max_bytes(ceiling(32769))
1302 ),
1303 Err(OreError::InitFailed)
1304 ));
1305 assert!(C::init_with(
1306 fixed_key(0x11),
1307 Options::default().with_max_bytes(ceiling(32768))
1308 )
1309 .is_ok());
1310 assert!(C::init_with(
1311 fixed_key(0x11),
1312 Options::default()
1313 .with_padding(Padding::None)
1314 .with_max_bytes(ceiling(MAX_STR_BYTES))
1315 )
1316 .is_ok());
1317 assert!(matches!(
1318 C::init_with(
1319 fixed_key(0x11),
1320 Options::default()
1321 .with_padding(Padding::None)
1322 .with_max_bytes(ceiling(MAX_STR_BYTES + 1))
1323 ),
1324 Err(OreError::InitFailed)
1325 ));
1326 }
1327
1328 const POLICIES: [Padding; 4] = [
1331 Padding::None,
1332 Padding::PowerOfTwo { min_bytes: 16 },
1333 Padding::PowerOfTwo { min_bytes: 0 },
1334 fixed_padding(48),
1335 ];
1336
1337 #[test]
1341 fn raw_symbols_are_checked() {
1342 let c = ore();
1343 assert!(matches!(
1344 c.encrypt_var(&[1, 64, 2]),
1345 Err(OreError::PrpError(_))
1346 ));
1347 assert!(matches!(
1348 c.encrypt_left_var(&[1, 64, 2]),
1349 Err(OreError::PrpError(_))
1350 ));
1351
1352 let unpadded = ore_with(Padding::None);
1353 let blocks =
1354 str_to_blocks("alice", &Options::default().with_padding(Padding::None)).unwrap();
1355 assert_eq!(
1356 unpadded
1357 .encrypt_left_var(blocks.as_bytes())
1358 .unwrap()
1359 .to_bytes(),
1360 unpadded.encrypt_left_str("alice").unwrap().to_bytes()
1361 );
1362 }
1363
1364 #[test]
1368 fn salt_separates_keys() {
1369 type C = OreAes128Bit6Chained;
1370 let plain = C::init(fixed_key(0x42)).unwrap();
1371 let empty = C::init_with_salt(fixed_key(0x42), &Context::empty()).unwrap();
1372 let col_a = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
1373 let col_a2 = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
1374 let col_b = C::init_with_salt(fixed_key(0x42), &salt(b"users.phone")).unwrap();
1375 let col_a_opts = C::init_with(
1376 fixed_key(0x42),
1377 Options::default().with_salt(&salt(b"users.email")),
1378 )
1379 .unwrap();
1380 assert_eq!(col_a.options().salt(), b"users.email");
1381
1382 let left = |c: &C| c.encrypt_left_str("alice").unwrap().to_bytes();
1383 assert_eq!(left(&plain), left(&empty));
1384 assert_eq!(left(&col_a), left(&col_a2));
1385 assert_eq!(left(&col_a), left(&col_a_opts));
1386 assert_ne!(left(&plain), left(&col_a));
1387 assert_ne!(left(&col_a), left(&col_b));
1388
1389 let a = col_a.encrypt_str("alice").unwrap().to_bytes();
1390 let b = col_b.encrypt_str("alice").unwrap().to_bytes();
1391 assert_ne!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
1392 assert_eq!(
1393 C::compare_raw_slices(&a, &col_a2.encrypt_str("alice").unwrap().to_bytes()),
1394 Some(Ordering::Equal)
1395 );
1396 assert_ne!(
1398 col_a.encrypt_query_plaintext(&u128_pt(7)).unwrap(),
1399 col_b.encrypt_query_plaintext(&u128_pt(7)).unwrap()
1400 );
1401 }
1402
1403 #[test]
1408 fn cross_salt_empty_strings_compare_equal() {
1409 type C = OreAes128Bit6Chained;
1410 let options = Options::default().with_padding(Padding::None);
1411 let a = C::init_with(
1412 fixed_key(0x42),
1413 options.clone().with_salt(&salt(b"users.email")),
1414 )
1415 .unwrap();
1416 let b = C::init_with(fixed_key(0x42), options.with_salt(&salt(b"users.phone"))).unwrap();
1417 let a = a.encrypt_str("").unwrap().to_bytes();
1418 let b = b.encrypt_str("").unwrap().to_bytes();
1419 assert_eq!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
1420 }
1421
1422 #[test]
1423 fn strings_over_the_wire_limit_are_rejected() {
1424 let c = ore();
1425 let too_long = "a".repeat(MAX_STR_BYTES + 1);
1426 assert!(matches!(
1427 c.encrypt_str(&too_long),
1428 Err(OreError::TooManyBlocks)
1429 ));
1430 assert!(matches!(
1431 c.encrypt_left_str(&too_long),
1432 Err(OreError::TooManyBlocks)
1433 ));
1434 }
1435
1436 #[test]
1440 fn raw_symbols_over_the_wire_limit_are_rejected() {
1441 let c = ore();
1442 let too_many = vec![64u8; u16::MAX as usize + 1];
1443 assert!(matches!(
1444 c.encrypt_var(&too_many),
1445 Err(OreError::TooManyBlocks)
1446 ));
1447 assert!(matches!(
1448 c.encrypt_left_var(&too_many),
1449 Err(OreError::TooManyBlocks)
1450 ));
1451 }
1452
1453 #[test]
1454 fn comparators_reject_out_of_domain_symbols() {
1455 let c = ore();
1456 let a = c.encrypt_str("apple").unwrap().to_bytes();
1457 let b = c.encrypt_str("apricot").unwrap().to_bytes();
1458 let q = c.encrypt_left_str("apple").unwrap().to_bytes();
1459 assert!(OreAes128Bit6Chained::compare_raw_slices(&a, &b).is_some());
1460
1461 let mut bad = a.clone();
1463 bad[HEADER_LEN] = DOMAIN as u8;
1464 let mut bad_q = q.clone();
1465 bad_q[HEADER_LEN] = DOMAIN as u8;
1466
1467 type C = OreAes128Bit6Chained;
1468 assert_eq!(C::compare_raw_slices(&bad, &b), None);
1469 assert_eq!(C::compare_raw_slices(&b, &bad), None);
1470 assert_eq!(C::compare_left_to_full(&bad_q, &b), None);
1471 assert_eq!(C::compare_left_to_full(&q, &bad), None);
1472 }
1473
1474 fn cmp(c: &OreAes128Bit6Chained, a: &str, b: &str) -> Ordering {
1475 let ca = c.encrypt_str(a).unwrap().to_bytes();
1476 let cb = c.encrypt_str(b).unwrap().to_bytes();
1477 OreAes128Bit6Chained::compare_raw_slices(&ca, &cb).unwrap()
1478 }
1479
1480 #[test]
1481 fn string_total_order_matches_lexicographic() {
1482 let words = [
1486 "",
1487 "a",
1488 "a\0b",
1489 "ab",
1490 "abc",
1491 "abd",
1492 "ac",
1493 "b",
1494 "banana",
1495 "bananas",
1496 "sixteen bytes ok",
1497 "sixteen bytes ok!",
1498 "thirty-two bytes, on the nose!!!",
1499 "thirty-two bytes, on the nose!!!!",
1500 "the quick brown fox jumps over the lazy dog",
1501 "the quick brown fox jumps over the lazy dog.",
1502 "zzz",
1503 ];
1504 for padding in POLICIES {
1505 let c = ore_with(padding);
1506 for &a in &words {
1507 for &b in &words {
1508 assert_eq!(
1509 cmp(&c, a, b),
1510 a.cmp(b),
1511 "order mismatch for {a:?} vs {b:?} under {padding:?}"
1512 );
1513 }
1514 }
1515 }
1516 }
1517
1518 #[test]
1519 fn power_of_two_lengths() {
1520 let p = |min_bytes, len| Padding::PowerOfTwo { min_bytes }.padded_len(len).unwrap();
1521 for len in 0..=16 {
1524 assert_eq!(p(16, len), 16);
1525 }
1526 assert_eq!(p(16, 17), 32);
1527 assert_eq!(p(16, 32), 32);
1528 assert_eq!(p(16, 33), 64);
1529 assert_eq!(p(16, 1000), 1024);
1530 assert_eq!(p(16, 1025), 2048);
1531 assert_eq!(p(0, 0), 0);
1534 assert_eq!(p(0, 1), 1);
1535 assert_eq!(p(0, 3), 4);
1536 assert_eq!(p(24, 20), 24);
1537 assert_eq!(p(24, 24), 24);
1538 assert_eq!(p(24, 25), 32);
1539 assert_eq!(p(16, 32768), 32768);
1542 for len in [32769, MAX_STR_BYTES] {
1543 assert!(matches!(
1544 Padding::PowerOfTwo { min_bytes: 16 }.padded_len(len),
1545 Err(OreError::TooManyBlocks)
1546 ));
1547 }
1548 }
1549
1550 #[test]
1551 fn padded_ciphertexts_reveal_only_the_bucket() {
1552 let c = ore();
1553 let size = |s: &str| c.encrypt_str(s).unwrap().to_bytes().len();
1554 let left_size = |s: &str| c.encrypt_left_str(s).unwrap().to_bytes().len();
1555 for s in ["", "a", "abc", "sixteen bytes ok"] {
1557 assert_eq!(size(s), total_len(num_blocks_6bit(16)), "{s:?}");
1558 assert_eq!(left_size(s), left_len(num_blocks_6bit(16)), "{s:?}");
1559 }
1560 assert_eq!(size("seventeen bytes!!"), total_len(num_blocks_6bit(32)));
1562 assert_eq!(
1563 size("thirty-two bytes, on the nose!!!"),
1564 total_len(num_blocks_6bit(32))
1565 );
1566 assert_eq!(
1567 size("thirty-two bytes, on the nose!!!!"),
1568 total_len(num_blocks_6bit(64))
1569 );
1570
1571 let fixed = ore_with(fixed_padding(48));
1572 for s in ["", "abc", &"x".repeat(48)] {
1573 assert_eq!(
1574 fixed.encrypt_str(s).unwrap().to_bytes().len(),
1575 total_len(num_blocks_6bit(48))
1576 );
1577 }
1578 }
1579
1580 #[test]
1581 fn padded_strings_must_not_end_in_nul() {
1582 for padding in POLICIES {
1583 let c = ore_with(padding);
1584 let full = c.encrypt_str("a\0");
1585 let left = c.encrypt_left_str("a\0");
1586 if padding == Padding::None {
1587 assert_eq!(cmp(&c, "a", "a\0"), Ordering::Less);
1589 } else {
1590 assert!(matches!(full, Err(OreError::TrailingNul)), "{:?}", padding);
1591 assert!(matches!(left, Err(OreError::TrailingNul)), "{:?}", padding);
1592 }
1593 assert!(c.encrypt_str("a\0b").is_ok());
1595 }
1596 }
1597
1598 #[test]
1599 fn fixed_padding_refuses_longer_strings() {
1600 let c = ore_with(fixed_padding(8));
1601 assert!(c.encrypt_str("12345678").is_ok());
1602 assert!(matches!(
1603 c.encrypt_str("123456789"),
1604 Err(OreError::ExceedsPadding)
1605 ));
1606 assert!(matches!(
1607 c.encrypt_left_str("123456789"),
1608 Err(OreError::ExceedsPadding)
1609 ));
1610 }
1611
1612 #[test]
1613 fn padding_policies_past_the_wire_limit_are_refused() {
1614 type C = OreAes128Bit6Chained;
1615 let max = MAX_STR_BYTES as u16;
1616 let with = |padding| Options::default().with_padding(padding);
1617 assert!(C::init_with(fixed_key(0x11), with(fixed_padding(max))).is_ok());
1618 assert!(matches!(
1619 C::init_with(fixed_key(0x11), with(fixed_padding(max + 1))),
1620 Err(OreError::InitFailed)
1621 ));
1622 assert!(C::init_with(
1624 fixed_key(0x11),
1625 with(Padding::PowerOfTwo { min_bytes: max })
1626 )
1627 .is_ok());
1628 assert!(matches!(
1629 C::init_with(
1630 fixed_key(0x11),
1631 with(Padding::PowerOfTwo { min_bytes: max + 1 })
1632 ),
1633 Err(OreError::InitFailed)
1634 ));
1635 let c = ore_with_max(Padding::default(), 32768);
1639 for len in [32769, MAX_STR_BYTES] {
1640 assert!(matches!(
1641 c.encrypt_str(&"a".repeat(len)),
1642 Err(OreError::TooManyBlocks)
1643 ));
1644 }
1645 }
1646
1647 #[test]
1650 fn comparators_refuse_mixed_policies() {
1651 type C = OreAes128Bit6Chained;
1652 for pa in POLICIES {
1653 for pb in POLICIES {
1654 let a = ore_with(pa);
1655 let b = ore_with(pb);
1656 let full_a = a.encrypt_str("abc").unwrap().to_bytes();
1657 let full_b = b.encrypt_str("abc").unwrap().to_bytes();
1658 let left_a = a.encrypt_left_str("abc").unwrap().to_bytes();
1659 let expected = (pa == pb).then_some(Ordering::Equal);
1660 assert_eq!(C::compare_raw_slices(&full_a, &full_b), expected);
1661 assert_eq!(C::compare_left_to_full(&left_a, &full_b), expected);
1662 }
1663 }
1664 }
1665
1666 #[test]
1667 fn padding_tag_round_trips_and_rejects_unknown_kinds() {
1668 let c = ore();
1669 let bytes = c.encrypt_str("abc").unwrap().to_bytes();
1670 let ct = VarCipherText::from_slice(&bytes).unwrap();
1671 assert_eq!(ct.padding(), Padding::default());
1672 assert_eq!(
1673 c.encrypt_left_str("abc").unwrap().padding(),
1674 Padding::default()
1675 );
1676
1677 type C = OreAes128Bit6Chained;
1678 let tag = WIRE_HEADER_LEN;
1679 let tampered = |at: usize, value: u8| {
1680 let mut t = bytes.clone();
1681 t[at] = value;
1682 t
1683 };
1684 for bad in [
1685 tampered(tag, 3), tampered(tag, 0), tampered(tag + 1, 0xff), ] {
1689 assert!(VarCipherText::from_slice(&bad).is_err());
1690 assert_eq!(C::compare_raw_slices(&bad, &bad), None);
1691 }
1692 }
1693
1694 fn small_alphabet_strings() -> Vec<String> {
1698 let mut out = vec![String::new()];
1699 let mut layer = vec![String::new()];
1700 for _ in 0..4 {
1701 layer = layer
1702 .iter()
1703 .flat_map(|s| ["\0", "a", "b"].iter().map(move |c| format!("{s}{c}")))
1704 .collect();
1705 out.extend(layer.iter().cloned());
1706 }
1707 out.retain(|s| !s.ends_with('\0'));
1708 for n in [15, 16, 17, 31, 32, 33] {
1709 out.push("a".repeat(n));
1710 out.push(format!("{}é", "a".repeat(n - 1)));
1712 }
1713 out
1714 }
1715
1716 #[test]
1720 fn small_alphabet_total_order_under_every_policy() {
1721 type C = OreAes128Bit6Chained;
1722 let strings = small_alphabet_strings();
1723 for padding in POLICIES {
1724 let c = ore_with(padding);
1725 let fulls: Vec<Vec<u8>> = strings
1726 .iter()
1727 .map(|s| c.encrypt_str(s).unwrap().to_bytes())
1728 .collect();
1729 let lefts: Vec<Vec<u8>> = strings
1730 .iter()
1731 .map(|s| c.encrypt_left_str(s).unwrap().to_bytes())
1732 .collect();
1733 for (i, a) in strings.iter().enumerate() {
1734 for (j, b) in strings.iter().enumerate() {
1735 let expected = Some(a.as_bytes().cmp(b.as_bytes()));
1736 assert_eq!(
1737 C::compare_raw_slices(&fulls[i], &fulls[j]),
1738 expected,
1739 "full {a:?} vs {b:?} under {padding:?}"
1740 );
1741 assert_eq!(
1742 C::compare_left_to_full(&lefts[i], &fulls[j]),
1743 expected,
1744 "left {a:?} vs {b:?} under {padding:?}"
1745 );
1746 }
1747 }
1748 }
1749 }
1750
1751 #[test]
1755 fn default_buckets_at_every_length() {
1756 type C = OreAes128Bit6Chained;
1757 let c = ore();
1758 let bucket = |n: usize| if n <= 16 { 16 } else { n.next_power_of_two() };
1759 let mut prev: Option<Vec<u8>> = None;
1760 for n in 0..=70 {
1761 let s = "a".repeat(n);
1762 let full = c.encrypt_str(&s).unwrap().to_bytes();
1763 let left = c.encrypt_left_str(&s).unwrap().to_bytes();
1764 assert_eq!(
1765 full.len(),
1766 total_len(num_blocks_6bit(bucket(n))),
1767 "{n} bytes"
1768 );
1769 assert_eq!(
1770 left.len(),
1771 left_len(num_blocks_6bit(bucket(n))),
1772 "{n} bytes"
1773 );
1774 let longer = c.encrypt_str(&format!("{s}b")).unwrap().to_bytes();
1775 assert_eq!(
1776 C::compare_raw_slices(&full, &longer),
1777 Some(Ordering::Less),
1778 "{n} bytes"
1779 );
1780 assert_eq!(
1781 C::compare_left_to_full(&left, &longer),
1782 Some(Ordering::Less),
1783 "{n} bytes"
1784 );
1785 if let Some(prev) = &prev {
1786 assert_eq!(
1787 C::compare_raw_slices(prev, &full),
1788 Some(Ordering::Less),
1789 "{n} bytes"
1790 );
1791 }
1792 prev = Some(full);
1793 }
1794 }
1795
1796 #[test]
1800 fn same_blocks_under_different_policies_do_not_compare() {
1801 type C = OreAes128Bit6Chained;
1802 let cases = [
1803 (
1804 Padding::PowerOfTwo { min_bytes: 16 },
1805 fixed_padding(16),
1806 "sixteen bytes ok",
1807 ),
1808 (
1809 Padding::PowerOfTwo { min_bytes: 16 },
1810 Padding::PowerOfTwo { min_bytes: 8 },
1811 "seventeen bytes!!",
1812 ),
1813 (
1814 fixed_padding(4),
1815 Padding::PowerOfTwo { min_bytes: 0 },
1816 "abc",
1817 ),
1818 ];
1819 for (pa, pb, s) in cases {
1820 let (a, b) = (ore_with(pa), ore_with(pb));
1821 let left_a = a.encrypt_left_str(s).unwrap().to_bytes();
1822 let left_b = b.encrypt_left_str(s).unwrap().to_bytes();
1823 assert_eq!(
1824 left_a[..WIRE_HEADER_LEN],
1825 left_b[..WIRE_HEADER_LEN],
1826 "{s:?}"
1827 );
1828 assert_ne!(left_a[..HEADER_LEN], left_b[..HEADER_LEN], "{s:?}");
1829 assert_eq!(left_a[HEADER_LEN..], left_b[HEADER_LEN..], "{s:?}");
1830 let full_b = b.encrypt_str(s).unwrap().to_bytes();
1831 assert_eq!(C::compare_left_to_full(&left_a, &full_b), None, "{s:?}");
1832 let full_a = a.encrypt_str(s).unwrap().to_bytes();
1833 assert_eq!(C::compare_raw_slices(&full_a, &full_b), None, "{s:?}");
1834 }
1835 }
1836
1837 #[test]
1842 #[ignore = "65535-block ciphertexts: about ten seconds unoptimised"]
1843 fn fixed_padding_at_the_wire_limit() {
1844 type C = OreAes128Bit6Chained;
1845 let c = ore_with_max(fixed_padding(MAX_STR_BYTES as u16), MAX_STR_BYTES);
1846 let full = c.encrypt_str("alice").unwrap().to_bytes();
1847 assert_eq!(full.len(), total_len(u16::MAX as usize));
1848 assert_eq!(VarCipherText::from_slice(&full).unwrap().to_bytes(), full);
1849 let left = c.encrypt_left_str("alicf").unwrap().to_bytes();
1850 assert_eq!(left.len(), left_len(u16::MAX as usize));
1851 assert_eq!(
1852 C::compare_left_to_full(&left, &full),
1853 Some(Ordering::Greater)
1854 );
1855 }
1856
1857 #[test]
1859 fn policies_admit_only_their_own_block_counts() {
1860 let blocks = num_blocks_6bit;
1861 let pow16 = Padding::PowerOfTwo { min_bytes: 16 };
1862 for count in [blocks(16), blocks(32), blocks(64), blocks(32768)] {
1863 assert!(pow16.admits_count(count), "{}", count);
1864 }
1865 for count in [0, blocks(8), blocks(16) + 1, blocks(48), blocks(65536)] {
1866 assert!(!pow16.admits_count(count), "{}", count);
1867 }
1868 let pow24 = Padding::PowerOfTwo { min_bytes: 24 };
1870 assert!(pow24.admits_count(blocks(24)));
1871 assert!(pow24.admits_count(blocks(32)));
1872 assert!(!pow24.admits_count(blocks(16)));
1873 let pow0 = Padding::PowerOfTwo { min_bytes: 0 };
1875 for len in [0, 1, 2, 4, 8, 1024] {
1876 assert!(pow0.admits_count(blocks(len)), "{}", len);
1877 }
1878 assert!(!pow0.admits_count(blocks(3)));
1879 let fixed = fixed_padding(48);
1880 assert!(fixed.admits_count(blocks(48)));
1881 assert!(!fixed.admits_count(blocks(48) - 1));
1882 for count in [0, 1, 1000, u16::MAX as usize] {
1883 assert!(Padding::None.admits_count(count));
1884 }
1885 }
1886
1887 #[test]
1891 fn parsers_reject_counts_the_policy_cannot_produce() {
1892 type C = OreAes128Bit6Chained;
1893 let retag = |bytes: &[u8], padding: Padding| {
1894 let mut t = bytes.to_vec();
1895 t[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&padding.to_wire());
1896 t
1897 };
1898 let unpadded = ore_with(Padding::None)
1900 .encrypt_str("abc")
1901 .unwrap()
1902 .to_bytes();
1903 let forged = retag(&unpadded, Padding::default());
1904 assert!(VarCipherText::from_slice(&forged).is_err());
1905 let genuine = ore().encrypt_str("abc").unwrap().to_bytes();
1906 assert_eq!(C::compare_raw_slices(&forged, &genuine), None);
1907 assert_eq!(C::compare_raw_slices(&forged, &forged), None);
1908 let left = retag(
1909 &ore_with(Padding::None)
1910 .encrypt_left_str("abc")
1911 .unwrap()
1912 .to_bytes(),
1913 Padding::default(),
1914 );
1915 assert_eq!(C::compare_left_to_full(&left, &genuine), None);
1916
1917 assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(48))).is_err());
1920 assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(16))).is_ok());
1921
1922 let mut empty = ore_with(Padding::None).encrypt_str("").unwrap().to_bytes();
1925 assert!(VarCipherText::from_slice(&empty).is_ok());
1926 empty[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&[2, 0, 0]);
1927 assert!(VarCipherText::from_slice(&empty).is_err());
1928 assert_eq!(C::compare_raw_slices(&empty, &empty), None);
1929 }
1930
1931 #[test]
1932 fn equality_same_plaintext_across_nonces() {
1933 let c = ore();
1934 let a = c.encrypt_str("hello world").unwrap().to_bytes();
1935 let b = c.encrypt_str("hello world").unwrap().to_bytes();
1936 assert_ne!(a, b, "nonces should differ"); assert_eq!(
1938 OreAes128Bit6Chained::compare_raw_slices(&a, &b),
1939 Some(Ordering::Equal)
1940 );
1941 }
1942
1943 #[test]
1944 fn serialize_roundtrip() {
1945 let c = ore();
1946 let ct = c.encrypt_str("roundtrip me").unwrap();
1947 let bytes = ct.to_bytes();
1948 let parsed = VarCipherText::from_slice(&bytes).unwrap();
1949 assert_eq!(parsed.to_bytes(), bytes);
1950 }
1951
1952 #[test]
1953 fn beyond_packed_cap() {
1954 let c = ore();
1956 let long_a = "aaaaaaaaaaaaaaaaaaaaaaaa"; let long_b = "aaaaaaaaaaaaaaaaaaaaaaab";
1958 assert_eq!(cmp(&c, long_a, long_b), Ordering::Less);
1959 assert_eq!(cmp(&c, long_a, long_a), Ordering::Equal);
1960 }
1961
1962 #[test]
1967 fn fixed_width_plaintexts_are_unpadded_terms() {
1968 let c = ore();
1969 let n = c.encrypt_plaintext(&u128_pt(7)).unwrap();
1970 let n_left = c.encrypt_query_plaintext(&u128_pt(7)).unwrap();
1971 assert_eq!(n.as_bytes().len(), total_len(22));
1972 assert_eq!(n_left.as_bytes().len(), left_len(22));
1973 assert_eq!(
1974 parse_chained_header(n.as_bytes()),
1975 Some((22, Padding::None))
1976 );
1977 assert_eq!(
1979 n_left.as_bytes(),
1980 c.encrypt_left_unpadded_bytes(&7u128.to_be_bytes())
1981 .unwrap()
1982 .to_bytes()
1983 );
1984 assert_eq!(
1985 OreAes128Bit6Chained::compare_left_to_full(n_left.as_bytes(), n.as_bytes()),
1986 Some(Ordering::Equal)
1987 );
1988 let s16_padded = c.encrypt_str("0123456789abcdef").unwrap().to_bytes();
1991 let s16 = ore_with(Padding::None)
1992 .encrypt_str("0123456789abcdef")
1993 .unwrap()
1994 .to_bytes();
1995 assert_eq!(
1996 parse_chained_header(&s16_padded).map(|(count, _)| count),
1997 Some(22)
1998 );
1999 assert_eq!(
2000 OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16_padded),
2001 None
2002 );
2003 assert!(OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16).is_some());
2004 }
2005
2006 #[test]
2009 fn only_text_is_padded() {
2010 let c = ore();
2011 let text = c.encrypt_plaintext(&text_pt("alice")).unwrap();
2012 assert_eq!(
2013 parse_chained_header(text.as_bytes()),
2014 Some((num_blocks_6bit(16), Padding::default()))
2015 );
2016 let bytes = c.encrypt_plaintext(&bytes_pt(b"alice")).unwrap();
2017 assert_eq!(
2018 parse_chained_header(bytes.as_bytes()),
2019 Some((num_blocks_6bit(6), Padding::None))
2020 );
2021 let n = c.encrypt_plaintext(&i128_pt(-1)).unwrap();
2022 assert_eq!(
2023 parse_chained_header(n.as_bytes()),
2024 Some((22, Padding::None))
2025 );
2026 assert!(c.encrypt_plaintext(&bytes_pt(b"\0")).is_ok());
2028 let small = ore_with_max(Padding::None, 8);
2030 assert!(small.encrypt_plaintext(&text_pt("1234567")).is_ok());
2031 assert!(matches!(
2032 small.encrypt_plaintext(&text_pt("12345678")),
2033 Err(OreError::TooLong)
2034 ));
2035 assert!(small.encrypt_plaintext(&bytes_pt(&[0u8; 7])).is_ok());
2038 assert!(matches!(
2039 small.encrypt_plaintext(&bytes_pt(&[0u8; 8])),
2040 Err(OreError::TooLong)
2041 ));
2042 assert!(matches!(
2043 small.encrypt_query_plaintext(&bytes_pt(&[0u8; 8])),
2044 Err(OreError::TooLong)
2045 ));
2046 assert!(small.encrypt_plaintext(&u128_pt(u128::MAX)).is_ok());
2047 }
2048
2049 #[test]
2052 fn unpadded_bytes_past_the_wire_limit_are_refused_by_length() {
2053 let c = ore();
2054 let too_wide = vec![0u8; MAX_STR_BYTES + 1];
2055 assert!(matches!(
2056 c.encrypt_unpadded_bytes(&too_wide),
2057 Err(OreError::TooManyBlocks)
2058 ));
2059 assert!(matches!(
2060 c.encrypt_left_unpadded_bytes(&too_wide),
2061 Err(OreError::TooManyBlocks)
2062 ));
2063 assert!(c
2064 .encrypt_left_unpadded_bytes(&too_wide[..MAX_STR_BYTES])
2065 .is_ok());
2066 }
2067
2068 #[test]
2069 fn signed_128_orders_across_zero() {
2070 let c = ore();
2071 let vals = [i128::MIN, -1, 0, 1, i128::MAX];
2072 let cts: Vec<Vec<u8>> = vals
2073 .iter()
2074 .map(|&v| c.encrypt_plaintext(&i128_pt(v)).unwrap().into_bytes())
2075 .collect();
2076 for (i, a) in cts.iter().enumerate() {
2077 for (j, b) in cts.iter().enumerate() {
2078 assert_eq!(
2079 OreAes128Bit6Chained::compare_raw_slices(a, b),
2080 Some(vals[i].cmp(&vals[j])),
2081 "{} vs {}",
2082 vals[i],
2083 vals[j]
2084 );
2085 }
2086 }
2087 }
2088
2089 #[test]
2090 fn cross_scheme_bytes_rejected() {
2091 let c = ore();
2092 let mut bytes = c.encrypt_str("x").unwrap().to_bytes();
2093 bytes[1] = 0x02; assert_eq!(
2095 OreAes128Bit6Chained::compare_raw_slices(&bytes, &bytes),
2096 None
2097 );
2098 }
2099
2100 #[test]
2101 fn left_query_path_and_artifact_rejection() {
2102 let c = ore();
2103 let left = c.encrypt_left_str("hi").unwrap().to_bytes();
2104 let full = c.encrypt_str("hi").unwrap().to_bytes();
2105 assert_eq!(
2107 OreAes128Bit6Chained::compare_left_to_full(&left, &full),
2108 Some(Ordering::Equal)
2109 );
2110 assert_eq!(OreAes128Bit6Chained::compare_raw_slices(&left, &full), None);
2113 assert_eq!(
2114 OreAes128Bit6Chained::compare_left_to_full(&full, &full),
2115 None
2116 );
2117 }
2118
2119 #[test]
2120 fn empty_string_sorts_first() {
2121 let c = ore();
2122 assert_eq!(cmp(&c, "", "a"), Ordering::Less);
2123 assert_eq!(cmp(&c, "", ""), Ordering::Equal);
2124 }
2125
2126 const PROP_MAX_BLOCKS: usize = 32;
2134
2135 fn to_domain(v: &[u8]) -> Vec<u8> {
2137 v.iter().take(PROP_MAX_BLOCKS).map(|b| b & 0x3f).collect()
2138 }
2139
2140 fn enc(c: &OreAes128Bit6Chained, x: &[u8]) -> Vec<u8> {
2141 c.encrypt_var(x).unwrap().to_bytes()
2142 }
2143
2144 quickcheck! {
2145 fn prop_block_order_matches_lex(a: Vec<u8>, b: Vec<u8>) -> bool {
2150 let c = ore();
2151 let (a, b) = (to_domain(&a), to_domain(&b));
2152 let (ea, eb) = (enc(&c, &a), enc(&c, &b));
2153 OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
2154 }
2155
2156 fn prop_left_query_matches_full(a: Vec<u8>, b: Vec<u8>) -> bool {
2160 let c = ore();
2161 let (a, b) = (to_domain(&a), to_domain(&b));
2162 let left_a = c.encrypt_left_var(&a).unwrap().to_bytes();
2163 let full_b = enc(&c, &b);
2164 OreAes128Bit6Chained::compare_left_to_full(&left_a, &full_b)
2165 == Some(a.cmp(&b))
2166 }
2167
2168 fn prop_shared_prefix_order(prefix: Vec<u8>, sa: Vec<u8>, sb: Vec<u8>) -> bool {
2172 let c = ore();
2173 let p = to_domain(&prefix);
2174 let mut a = p.clone();
2175 a.extend(to_domain(&sa));
2176 a.truncate(PROP_MAX_BLOCKS);
2177 let mut b = p;
2178 b.extend(to_domain(&sb));
2179 b.truncate(PROP_MAX_BLOCKS);
2180 let (ea, eb) = (enc(&c, &a), enc(&c, &b));
2181 OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
2182 }
2183
2184 fn prop_string_order_matches_str(a: String, b: String) -> bool {
2191 let a: String = a.chars().take(12).collect();
2192 let b: String = b.chars().take(12).collect();
2193 let (a, b) = (a.trim_end_matches('\0'), b.trim_end_matches('\0'));
2194 POLICIES.iter().all(|&padding| {
2195 let c = ore_with(padding);
2196 let ea = c.encrypt_str(a).unwrap().to_bytes();
2197 let eb = c.encrypt_str(b).unwrap().to_bytes();
2198 OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
2199 })
2200 }
2201
2202 fn prop_padded_prefix_order(prefix: String, tail: String) -> bool {
2206 let a: String = prefix.chars().take(20).collect();
2207 let a = a.trim_end_matches('\0');
2208 let b: String = a.chars().chain(tail.chars().take(8)).collect();
2209 let b = b.trim_end_matches('\0');
2210 POLICIES[1..3].iter().all(|&padding| {
2211 let c = ore_with(padding);
2212 let ea = c.encrypt_str(a).unwrap().to_bytes();
2213 let eb = c.encrypt_str(b).unwrap().to_bytes();
2214 OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
2215 })
2216 }
2217
2218 fn prop_power_of_two_buckets(a: u16, b: u16) -> bool {
2221 let (a, b) = (usize::from(a) / 2, usize::from(b) / 2);
2223 let p = |n| Padding::PowerOfTwo { min_bytes: 0 }.padded_len(n).unwrap();
2224 let pa = p(a);
2225 pa >= a && pa < 2 * a.max(1) && (a > b || pa <= p(b)) && p(pa) == pa
2226 }
2227
2228 fn prop_padding_is_nul_extension(s: String) -> bool {
2233 let s: String = s.chars().take(40).collect();
2234 let s = s.trim_end_matches('\0');
2235 let unpadded = ore_with(Padding::None);
2236 POLICIES.iter().all(|&padding| {
2237 let c = ore_with(padding);
2238 let Ok(padded) = padding.padded_len(s.len()) else {
2239 return matches!(padding, Padding::Fixed { .. })
2240 && matches!(c.encrypt_left_str(s), Err(OreError::ExceedsPadding))
2241 && matches!(c.encrypt_str(s), Err(OreError::ExceedsPadding));
2242 };
2243 let mut extended = s.to_owned();
2244 extended.extend(std::iter::repeat_n('\0', padded - s.len()));
2245 let left = c.encrypt_left_str(s).unwrap();
2246 let a = left.to_bytes();
2247 let b = unpadded.encrypt_left_str(&extended).unwrap().to_bytes();
2248 left.padding() == padding
2249 && a[..WIRE_HEADER_LEN] == b[..WIRE_HEADER_LEN]
2250 && a[HEADER_LEN..] == b[HEADER_LEN..]
2251 })
2252 }
2253
2254 fn prop_string_equality_under_every_policy(s: String) -> bool {
2258 type C = OreAes128Bit6Chained;
2259 let s: String = s.chars().take(12).collect();
2260 let s = s.trim_end_matches('\0');
2261 POLICIES.iter().all(|&padding| {
2262 let c = ore_with(padding);
2263 let a = c.encrypt_str(s).unwrap().to_bytes();
2264 let b = c.encrypt_str(s).unwrap().to_bytes();
2265 let l = c.encrypt_left_str(s).unwrap().to_bytes();
2266 C::compare_raw_slices(&a, &b) == Some(Ordering::Equal)
2267 && C::compare_left_to_full(&l, &b) == Some(Ordering::Equal)
2268 && VarCipherText::from_slice(&a)
2269 .map(|ct| ct.to_bytes() == a && ct.padding() == padding)
2270 .unwrap_or(false)
2271 })
2272 }
2273
2274 fn prop_padding_refuses_exactly_trailing_nul(s: String, nul: bool) -> bool {
2277 let mut s: String = s.chars().take(11).collect();
2278 if nul {
2279 s.push('\0');
2280 }
2281 let ends_in_nul = s.ends_with('\0');
2282 POLICIES.iter().all(|&padding| {
2283 let c = ore_with(padding);
2284 let (full, left) = (c.encrypt_str(&s), c.encrypt_left_str(&s));
2285 if padding != Padding::None && ends_in_nul {
2286 matches!(full, Err(OreError::TrailingNul))
2287 && matches!(left, Err(OreError::TrailingNul))
2288 } else {
2289 full.is_ok() && left.is_ok()
2290 }
2291 })
2292 }
2293
2294 fn prop_parsers_never_panic(bytes: Vec<u8>, at: usize, value: u8) -> bool {
2297 type C = OreAes128Bit6Chained;
2298 let good = ore().encrypt_str("alice").unwrap().to_bytes();
2299 let mut changed = good.clone();
2300 changed[at % good.len()] = value;
2301 for x in [&bytes, &changed] {
2302 let _ = VarCipherText::from_slice(x);
2303 let _ = C::compare_raw_slices(x, x);
2304 let _ = C::compare_raw_slices(x, &good);
2305 let _ = C::compare_left_to_full(x, &good);
2306 let _ = C::compare_left_to_full(&good, x);
2307 }
2308 true
2309 }
2310
2311 fn prop_u128_order(a: u128, b: u128) -> bool {
2314 let c = ore();
2315 let ca = c.encrypt_plaintext(&u128_pt(a)).unwrap();
2316 let cb = c.encrypt_plaintext(&u128_pt(b)).unwrap();
2317 let la = c.encrypt_query_plaintext(&u128_pt(a)).unwrap();
2318 OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2319 && OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2320 }
2321
2322 fn prop_i128_order(a: i128, b: i128) -> bool {
2323 let c = ore();
2324 let ca = c.encrypt_plaintext(&i128_pt(a)).unwrap();
2325 let cb = c.encrypt_plaintext(&i128_pt(b)).unwrap();
2326 let la = c.encrypt_query_plaintext(&i128_pt(a)).unwrap();
2327 OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2328 && OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
2329 }
2330
2331 fn prop_equality_across_nonces(x: Vec<u8>) -> bool {
2334 let c = ore();
2335 let x = to_domain(&x);
2336 let (a, b) = (enc(&c, &x), enc(&c, &x));
2337 let equal = OreAes128Bit6Chained::compare_raw_slices(&a, &b)
2338 == Some(Ordering::Equal);
2339 let distinct = x.is_empty() || a != b;
2342 equal && distinct
2343 }
2344
2345 fn prop_left_deterministic_and_consistent(x: Vec<u8>) -> bool {
2349 let c = ore();
2350 let x = to_domain(&x);
2351 let l1 = c.encrypt_left_var(&x).unwrap().to_bytes();
2352 let l2 = c.encrypt_left_var(&x).unwrap().to_bytes();
2353 let full = c.encrypt_var(&x).unwrap();
2354 l1 == l2 && full.left.to_bytes() == l1
2355 }
2356
2357 fn prop_serialize_roundtrip(x: Vec<u8>) -> bool {
2359 let c = ore();
2360 let x = to_domain(&x);
2361 let bytes = enc(&c, &x);
2362 match VarCipherText::from_slice(&bytes) {
2363 Ok(ct) => ct.to_bytes() == bytes,
2364 Err(_) => false,
2365 }
2366 }
2367 }
2368
2369 fn block_tables(ore: &OreAes128Bit6Chained, s: &str) -> Vec<Vec<u8>> {
2372 let blocks = str_to_blocks(s, &ore.options).unwrap();
2373 let mut acc = CmacAccumulator::new(&ore.k_acc);
2374 let mut needles = Vec::new();
2375 for (n, &sym) in blocks.as_bytes().iter().enumerate() {
2376 let prp = ore.prp_at(&acc, n as u16);
2377 let symbols = (0..64).map(crate::primitives::Symbol::<64>::from_low_bits);
2378 needles.push(symbols.clone().map(|i| prp.permute(i).get()).collect());
2379 needles.push(symbols.map(|i| prp.invert(i).get()).collect());
2380 acc.absorb(&prefix_block(n as u16, sym));
2381 }
2382 needles
2383 }
2384
2385 fn assert_no_block_tables(
2386 encrypt: fn(&OreAes128Bit6Chained, &str),
2387 unscrubbed: fn(&OreAes128Bit6Chained, &str),
2388 ) {
2389 use crate::primitives::stack::{residue, SCRUB_BYTES};
2390 const S: &str = "a chained residue test string";
2391 let needles = block_tables(&ore(), S);
2392
2393 let dead = residue::after(move || unscrubbed(&ore(), S));
2395 assert!(needles.iter().any(|n| residue::contains(&dead, n)));
2396 let depth = residue::depth(&dead);
2397 assert!(
2398 depth < SCRUB_BYTES,
2399 "encryption reached {} bytes of stack, past the {}-byte scrub",
2400 depth,
2401 SCRUB_BYTES
2402 );
2403
2404 let dead = residue::after(move || encrypt(&ore(), S));
2405 for (i, needle) in needles.iter().enumerate() {
2406 assert!(
2407 !residue::contains(&dead, needle),
2408 "block {} {} left in dead stack",
2409 i / 2,
2410 ["permutation", "inverse"][i % 2]
2411 );
2412 }
2413 }
2414
2415 #[test]
2416 fn encrypt_str_leaves_no_prp_tables_on_the_stack() {
2417 assert_no_block_tables(
2418 |ore, s| {
2419 core::hint::black_box(ore.encrypt_str(s).unwrap());
2420 },
2421 |ore, s| {
2422 let blocks = str_to_blocks(s, &ore.options).unwrap();
2423 core::hint::black_box(ore.encrypt_blocks(&blocks, ore.padding()).unwrap());
2424 },
2425 );
2426 }
2427
2428 fn assert_no_large_plaintext(encrypt: fn(&OreAes128Bit6Chained, &OrderPlaintext)) {
2432 use crate::primitives::stack::{residue, SCRUB_BYTES};
2433 const LEN: usize = MAX_STR_BYTES - 1;
2435 fn raw() -> Vec<u8> {
2436 (0..LEN).map(|i| (i * 37 + 11) as u8).collect()
2437 }
2438 let p = raw();
2441 let needles: Vec<Vec<u8>> = [0, LEN / 2, LEN - 64]
2442 .iter()
2443 .map(|&at| p[at..at + 64].to_vec())
2444 .collect();
2445
2446 if LEN > SCRUB_BYTES {
2449 let dead = residue::after(|| {
2450 let p = raw();
2451 stack::scrubbed(|| {
2452 let mut copy = [0u8; LEN];
2453 copy.copy_from_slice(&p);
2454 core::hint::black_box(©);
2455 });
2456 });
2457 assert!(needles.iter().any(|n| residue::contains(&dead, n)));
2458 }
2459
2460 let dead = residue::after(move || {
2462 encrypt(
2463 &ore_with_max(Padding::None, MAX_STR_BYTES),
2464 &bytes_pt(&raw()),
2465 )
2466 });
2467 for needle in &needles {
2468 assert!(
2469 !residue::contains(&dead, needle),
2470 "plaintext left in dead stack"
2471 );
2472 }
2473 }
2474
2475 #[test]
2476 fn encrypt_plaintext_leaves_no_large_array_on_the_stack() {
2477 assert_no_large_plaintext(|ore, p| {
2478 core::hint::black_box(ore.encrypt_plaintext(p).unwrap());
2479 });
2480 }
2481
2482 #[test]
2483 fn encrypt_query_plaintext_leaves_no_large_array_on_the_stack() {
2484 assert_no_large_plaintext(|ore, p| {
2485 core::hint::black_box(ore.encrypt_query_plaintext(p).unwrap());
2486 });
2487 }
2488
2489 #[test]
2490 fn encrypt_left_str_leaves_no_prp_tables_on_the_stack() {
2491 assert_no_block_tables(
2492 |ore, s| {
2493 core::hint::black_box(ore.encrypt_left_str(s).unwrap());
2494 },
2495 |ore, s| {
2496 let blocks = str_to_blocks(s, &ore.options).unwrap();
2497 core::hint::black_box(ore.encrypt_left_blocks(&blocks, ore.padding()).unwrap());
2498 },
2499 );
2500 }
2501
2502 #[test]
2506 fn every_term_draws_a_fresh_nonce() {
2507 let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
2508 ore.encrypt_plaintext(p).unwrap().into_bytes()
2509 };
2510 let a = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2511 let b = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2512 let (a1, a2, b1) = (
2513 term_bytes(&a, &text_pt("alice")),
2514 term_bytes(&a, &text_pt("alice")),
2515 term_bytes(&b, &text_pt("alice")),
2516 );
2517 assert_ne!(a1, a2, "one cipher reused a nonce");
2518 assert_ne!(a1, b1, "two ciphers drew the same nonce stream");
2519 assert_eq!(
2520 OreAes128Bit6Chained::compare_raw_slices(&a1, &b1),
2521 Some(Ordering::Equal)
2522 );
2523 }
2524
2525 #[test]
2529 fn a_poisoned_nonce_lock_still_encrypts() {
2530 let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
2531 ore.encrypt_plaintext(p).unwrap().into_bytes()
2532 };
2533 let ore = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
2534 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2535 let _guard = ore.rng.lock().unwrap();
2536 panic!("poison the nonce lock");
2537 }));
2538 assert!(ore.rng.is_poisoned());
2539 let (a, b) = (
2540 term_bytes(&ore, &text_pt("alice")),
2541 term_bytes(&ore, &text_pt("alice")),
2542 );
2543 assert_ne!(a, b, "a poisoned lock reused a nonce");
2544 assert_eq!(
2545 OreAes128Bit6Chained::compare_raw_slices(&a, &b),
2546 Some(Ordering::Equal)
2547 );
2548 }
2549}