use std::cmp::Ordering;
use std::convert::TryFrom;
use std::num::{NonZeroU16, NonZeroUsize};
use std::sync::Mutex;
use rand::TryRng;
use subtle_ng::{Choice, ConditionallySelectable, ConstantTimeEq};
use vitaminc_context::Context;
use vitaminc_ore::{OrderPlaintext, OrderTarget};
use vitaminc_protected::{Controlled, Protected};
use vitaminc_random::SafeRand;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
#[cfg(test)]
use crate::ciphertext::ParseError;
use crate::ciphertext::{parse_header, WireHeader, WIRE_HEADER_LEN};
use crate::primitives::cmac::{final_block, prefix_block, Branch, CmacAccumulator, WIDTH_BIT6};
use crate::primitives::hash::FixedPiZ2Hash;
use crate::primitives::prp::LemireFyPrp;
use crate::primitives::{stack, AesBlock, Hash, HashKey, Prp};
use crate::scheme::decompose::{num_blocks_6bit, Blocks6};
use crate::scheme::keys;
use crate::scheme::width::FirstDiff;
use crate::{OreError, OreScheme, Query, Term};
const VERSION: u8 = 0x02;
pub(crate) const SCHEME_ID: u8 = 0x03;
const WIRE: WireHeader = WireHeader {
version: VERSION,
scheme_id: SCHEME_ID,
};
const DOMAIN: usize = 64;
const STREAM_BLOCKS: usize = 32;
const F_LEN: usize = 16;
const RIGHT_LEN: usize = DOMAIN / 8; const PADDING_LEN: usize = 3;
const HEADER_LEN: usize = WIRE_HEADER_LEN + PADDING_LEN;
const NONCE_LEN: usize = 16;
const ROOT_LABEL: [u8; 16] = *b"ORE.v2.chainroot";
const _: () = assert!(
ROOT_LABEL[15] > 14,
"root label collides with a legacy PRF input"
);
const ACC_KEY_LABEL: [u8; 16] = *b"ORE.v2.chain.acc";
#[inline]
fn total_len(count: usize) -> usize {
HEADER_LEN + count + count * F_LEN + NONCE_LEN + count * RIGHT_LEN
}
#[inline]
fn left_len(count: usize) -> usize {
HEADER_LEN + count + count * F_LEN
}
#[inline]
fn xt_at(s: &[u8], i: usize) -> u8 {
s[HEADER_LEN + i]
}
#[inline]
fn f_at(s: &[u8], count: usize, i: usize) -> &[u8] {
let o = HEADER_LEN + count + i * F_LEN;
&s[o..o + F_LEN]
}
#[inline]
fn nonce_at(s: &[u8], count: usize) -> &[u8] {
let o = HEADER_LEN + count + count * F_LEN;
&s[o..o + NONCE_LEN]
}
#[inline]
fn right_at(s: &[u8], count: usize, i: usize) -> &[u8] {
let o = HEADER_LEN + count + count * F_LEN + NONCE_LEN + i * RIGHT_LEN;
&s[o..o + RIGHT_LEN]
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Padding {
None,
PowerOfTwo {
min_bytes: u16,
},
Fixed {
max_bytes: NonZeroU16,
},
}
impl Default for Padding {
fn default() -> Self {
Padding::PowerOfTwo { min_bytes: 16 }
}
}
impl Padding {
pub fn padded_len(self, len: usize) -> Result<usize, OreError> {
let padded = match self {
Padding::None => len,
Padding::PowerOfTwo { min_bytes } if len <= min_bytes.into() => min_bytes.into(),
Padding::PowerOfTwo { .. } => len
.checked_next_power_of_two()
.ok_or(OreError::TooManyBlocks)?,
Padding::Fixed { max_bytes } if len <= max_bytes.get().into() => max_bytes.get().into(),
Padding::Fixed { .. } => return Err(OreError::ExceedsPadding),
};
if padded > MAX_STR_BYTES {
return Err(OreError::TooManyBlocks);
}
Ok(padded)
}
fn to_wire(self) -> [u8; PADDING_LEN] {
let (kind, n) = match self {
Padding::None => (0, 0),
Padding::PowerOfTwo { min_bytes } => (1, min_bytes),
Padding::Fixed { max_bytes } => (2, max_bytes.get()),
};
let [hi, lo] = n.to_be_bytes();
[kind, hi, lo]
}
fn from_wire(tag: [u8; PADDING_LEN]) -> Option<Self> {
let [kind, hi, lo] = tag;
let n = u16::from_be_bytes([hi, lo]);
let padding = match kind {
0 if n == 0 => Padding::None,
1 => Padding::PowerOfTwo { min_bytes: n },
2 => Padding::Fixed {
max_bytes: NonZeroU16::new(n)?,
},
_ => return None,
};
padding.padded_len(0).ok().map(|_| padding)
}
fn admits_count(self, count: usize) -> bool {
match self {
Padding::None => true,
Padding::Fixed { max_bytes } => count == num_blocks_6bit(max_bytes.get().into()),
Padding::PowerOfTwo { min_bytes } => {
let min_bytes = usize::from(min_bytes);
count == num_blocks_6bit(min_bytes)
|| (0..=MAX_STR_BYTES.ilog2()).any(|k| {
let bucket = 1usize << k;
bucket > min_bytes && count == num_blocks_6bit(bucket)
})
}
}
}
}
pub const DEFAULT_MAX_STR_BYTES: NonZeroUsize = match NonZeroUsize::new(1024) {
Some(n) => n,
None => NonZeroUsize::MIN,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
salt: Vec<u8>,
padding: Padding,
max_bytes: NonZeroUsize,
}
impl Default for Options {
fn default() -> Self {
Self {
salt: Vec::new(),
padding: Padding::default(),
max_bytes: DEFAULT_MAX_STR_BYTES,
}
}
}
impl Options {
pub fn new() -> Self {
Self::default()
}
pub fn with_salt(self, salt: &Context<'_>) -> Self {
Self {
salt: salt.as_bytes().to_vec(),
..self
}
}
pub fn with_padding(self, padding: Padding) -> Self {
Self { padding, ..self }
}
pub fn with_max_bytes(self, max_bytes: NonZeroUsize) -> Self {
Self { max_bytes, ..self }
}
pub fn salt(&self) -> &[u8] {
&self.salt
}
pub fn padding(&self) -> Padding {
self.padding
}
pub fn max_bytes(&self) -> NonZeroUsize {
self.ceiling()
}
fn ceiling(&self) -> NonZeroUsize {
match self.padding {
Padding::Fixed { max_bytes } => self.max_bytes.min(NonZeroUsize::from(max_bytes)),
_ => self.max_bytes,
}
}
fn check(&self) -> Result<(), OreError> {
self.padding
.padded_len(0)
.map_err(|_| OreError::InitFailed)?;
self.padding
.padded_len(self.ceiling().get())
.map_err(|_| OreError::InitFailed)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub(crate) struct VarLeft {
xt: Vec<u8>,
f: Vec<[u8; F_LEN]>,
padding: Padding,
}
#[derive(Clone, Debug)]
pub(crate) struct VarRight {
nonce: [u8; NONCE_LEN],
blocks: Vec<[u8; RIGHT_LEN]>,
}
#[derive(Clone, Debug)]
pub(crate) struct VarCipherText {
left: VarLeft,
right: VarRight,
}
impl VarLeft {
pub fn to_bytes(&self) -> Vec<u8> {
let count = self.xt.len();
let mut out = Vec::with_capacity(left_len(count));
write_header(count, self.padding, &mut out);
out.extend_from_slice(&self.xt);
for fb in &self.f {
out.extend_from_slice(fb);
}
out
}
#[cfg(test)]
pub fn padding(&self) -> Padding {
self.padding
}
}
#[cfg(test)]
fn parse_left_view(data: &[u8], count: usize, padding: Padding) -> VarLeft {
let xt = data[HEADER_LEN..HEADER_LEN + count].to_vec();
let mut f = Vec::with_capacity(count);
for n in 0..count {
let mut fb = [0u8; F_LEN];
fb.copy_from_slice(f_at(data, count, n));
f.push(fb);
}
VarLeft { xt, f, padding }
}
impl VarCipherText {
pub fn to_bytes(&self) -> Vec<u8> {
let count = self.left.xt.len();
let mut out = Vec::with_capacity(total_len(count));
write_header(count, self.left.padding, &mut out);
out.extend_from_slice(&self.left.xt);
for fb in &self.left.f {
out.extend_from_slice(fb);
}
out.extend_from_slice(&self.right.nonce);
for rb in &self.right.blocks {
out.extend_from_slice(rb);
}
out
}
#[cfg(test)]
pub fn padding(&self) -> Padding {
self.left.padding
}
#[cfg(test)]
pub fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
let (count, padding) = parse_chained_header(data).ok_or(ParseError)?;
if data.len() != total_len(count) {
return Err(ParseError);
}
if !symbols_in_domain(data, count) {
return Err(ParseError);
}
let left = parse_left_view(data, count, padding);
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(nonce_at(data, count));
let mut blocks = Vec::with_capacity(count);
for n in 0..count {
let mut rb = [0u8; RIGHT_LEN];
rb.copy_from_slice(right_at(data, count, n));
blocks.push(rb);
}
Ok(VarCipherText {
left,
right: VarRight { nonce, blocks },
})
}
}
fn write_header(count: usize, padding: Padding, out: &mut Vec<u8>) {
WIRE.write(u16::try_from(count).unwrap_or(u16::MAX), out);
out.extend_from_slice(&padding.to_wire());
}
fn parse_chained_header(view: &[u8]) -> Option<(usize, Padding)> {
let ((ver, sid, count), body) = parse_header(view).ok()?;
if ver != VERSION || sid != SCHEME_ID {
return None;
}
let tag = <[u8; PADDING_LEN]>::try_from(body.get(..PADDING_LEN)?).ok()?;
let padding = Padding::from_wire(tag)?;
padding.admits_count(count).then_some((count, padding))
}
fn parse_pair(a: &[u8], b: &[u8]) -> Option<(usize, usize)> {
let (ca, pa) = parse_chained_header(a)?;
let (cb, pb) = parse_chained_header(b)?;
(pa == pb).then_some((ca, cb))
}
pub struct OreAes128Bit6Chained {
k_acc: [u8; 16],
options: Options,
rng: Mutex<SafeRand>,
}
impl std::fmt::Debug for OreAes128Bit6Chained {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OreAes128Bit6Chained")
.field("options", &self.options)
.finish_non_exhaustive()
}
}
impl OreAes128Bit6Chained {
pub fn init(key: Protected<[u8; 16]>) -> Result<Self, OreError> {
Self::init_with(key, Options::default())
}
pub fn init_with_salt(key: Protected<[u8; 16]>, salt: &Context<'_>) -> Result<Self, OreError> {
Self::init_with(key, Options::default().with_salt(salt))
}
pub fn init_with(key: Protected<[u8; 16]>, options: Options) -> Result<Self, OreError> {
Self::init_with_rng(key, options, SafeRand::from_entropy()?)
}
#[cfg(any(test, feature = "test-support"))]
pub fn init_seeded(
key: Protected<[u8; 16]>,
options: Options,
seed: [u8; 32],
) -> Result<Self, OreError> {
use vitaminc_random::SeedableRng;
Self::init_with_rng(key, options, SafeRand::from_seed(seed))
}
fn init_with_rng(
key: Protected<[u8; 16]>,
options: Options,
rng: SafeRand,
) -> Result<Self, OreError> {
options.check()?;
let k_salt = keys::salted(&keys::root(key.risky_ref(), &ROOT_LABEL), options.salt());
let k_acc = *keys::subkey(&k_salt, &ACC_KEY_LABEL);
Ok(Self {
k_acc,
options,
rng: Mutex::new(rng),
})
}
fn fill_nonce(&self, nonce: &mut [u8; NONCE_LEN]) {
let mut rng = self
.rng
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match rng.try_fill_bytes(nonce) {
Ok(()) => {}
Err(never) => match never {},
}
}
pub fn options(&self) -> &Options {
&self.options
}
pub fn padding(&self) -> Padding {
self.options.padding()
}
fn prp_at(&self, acc: &CmacAccumulator, n: u16) -> LemireFyPrp<DOMAIN> {
let mut stream = [0u8; STREAM_BLOCKS * 16];
for (c, chunk) in stream.chunks_mut(16).enumerate() {
chunk.copy_from_slice(&acc.finalize(&final_block(
Branch::PrpStream,
n,
c as u16,
WIDTH_BIT6,
)));
}
let prp = LemireFyPrp::<DOMAIN>::from_stream(&stream);
stream.zeroize();
prp
}
#[cfg(test)]
pub(crate) fn encrypt_var(&self, x: &[u8]) -> Result<VarCipherText, OreError> {
stack::scrubbed(|| self.encrypt_blocks(&check_symbols(x)?, Padding::None))
}
fn encrypt_blocks<B: AsRef<[u8]>>(
&self,
x: &Blocks6<B>,
padding: Padding,
) -> Result<VarCipherText, OreError> {
let count = x.len();
if count > u16::MAX as usize {
return Err(OreError::TooManyBlocks);
}
let mut acc = CmacAccumulator::new(&self.k_acc);
let mut nonce = [0u8; NONCE_LEN];
self.fill_nonce(&mut nonce);
let hasher = FixedPiZ2Hash::new(HashKey::from_slice(&nonce));
let mut xt = Vec::with_capacity(count);
let mut f = Vec::with_capacity(count);
let mut blocks = Vec::with_capacity(count);
let mut ro = [AesBlock::default(); DOMAIN];
for n in 0..count {
let sym = x.symbol(n);
let n16 = n as u16;
let prp = self.prp_at(&acc, n16);
let permuted = prp.permute(sym).get();
xt.push(permuted);
for (j, blk) in ro.iter_mut().enumerate() {
blk.copy_from_slice(&acc.finalize(&final_block(
Branch::RoKey,
n16,
j as u16,
WIDTH_BIT6,
)));
}
f.push(acc.finalize(&final_block(
Branch::RoKey,
n16,
permuted as u16,
WIDTH_BIT6,
)));
let mut rb = [0u8; RIGHT_LEN];
hasher.hash_all_into(&mut ro, &mut rb);
prp.indicator_mask_xor(sym, &mut rb);
blocks.push(rb);
acc.absorb(&prefix_block(n16, sym.get()));
}
for blk in ro.iter_mut() {
blk.as_mut_slice().zeroize();
}
Ok(VarCipherText {
left: VarLeft { xt, f, padding },
right: VarRight { nonce, blocks },
})
}
#[cfg(test)]
pub(crate) fn encrypt_left_var(&self, x: &[u8]) -> Result<VarLeft, OreError> {
stack::scrubbed(|| self.encrypt_left_blocks(&check_symbols(x)?, Padding::None))
}
fn encrypt_left_blocks<B: AsRef<[u8]>>(
&self,
x: &Blocks6<B>,
padding: Padding,
) -> Result<VarLeft, OreError> {
let count = x.len();
if count > u16::MAX as usize {
return Err(OreError::TooManyBlocks);
}
let mut acc = CmacAccumulator::new(&self.k_acc);
let mut xt = Vec::with_capacity(count);
let mut f = Vec::with_capacity(count);
for n in 0..count {
let sym = x.symbol(n);
let n16 = n as u16;
let prp = self.prp_at(&acc, n16);
let permuted = prp.permute(sym).get();
xt.push(permuted);
f.push(acc.finalize(&final_block(
Branch::RoKey,
n16,
permuted as u16,
WIDTH_BIT6,
)));
acc.absorb(&prefix_block(n16, sym.get()));
}
Ok(VarLeft { xt, f, padding })
}
#[cfg(test)]
pub(crate) fn encrypt_str(&self, s: &str) -> Result<VarCipherText, OreError> {
self.encrypt_padded_bytes(s.as_bytes())
}
#[cfg(test)]
pub(crate) fn encrypt_left_str(&self, s: &str) -> Result<VarLeft, OreError> {
self.encrypt_left_padded_bytes(s.as_bytes())
}
pub(crate) fn encrypt_padded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
stack::scrubbed(|| {
self.encrypt_blocks(
&padded_bytes_to_blocks(bytes, &self.options)?,
self.padding(),
)
})
}
pub(crate) fn encrypt_left_padded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
stack::scrubbed(|| {
self.encrypt_left_blocks(
&padded_bytes_to_blocks(bytes, &self.options)?,
self.padding(),
)
})
}
pub(crate) fn encrypt_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
stack::scrubbed(|| self.encrypt_blocks(&bytes_to_blocks(bytes)?, Padding::None))
}
pub(crate) fn encrypt_left_unpadded_bytes(&self, bytes: &[u8]) -> Result<VarLeft, OreError> {
stack::scrubbed(|| self.encrypt_left_blocks(&bytes_to_blocks(bytes)?, Padding::None))
}
}
impl crate::sealed::Sealed for OreAes128Bit6Chained {}
enum Path {
Padded,
Unpadded,
}
impl OreAes128Bit6Chained {
fn path(&self, plaintext: &OrderPlaintext) -> Result<Path, OreError> {
match plaintext.target() {
OrderTarget::Bytes => {
if plaintext.bytes().risky_ref().len() > self.options.max_bytes().get() {
return Err(OreError::TooLong);
}
Ok(Path::Unpadded)
}
target if target.width().is_some() => Ok(Path::Unpadded),
_ => Ok(Path::Padded),
}
}
}
impl OreScheme for OreAes128Bit6Chained {
fn encrypt_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Term, OreError> {
let bytes = plaintext.bytes().risky_ref();
let ct = match self.path(plaintext)? {
Path::Padded => self.encrypt_padded_bytes(bytes)?,
Path::Unpadded => self.encrypt_unpadded_bytes(bytes)?,
};
Ok(Term::new(ct.to_bytes()))
}
fn encrypt_query_plaintext(&self, plaintext: &OrderPlaintext) -> Result<Query, OreError> {
let bytes = plaintext.bytes().risky_ref();
let left = match self.path(plaintext)? {
Path::Padded => self.encrypt_left_padded_bytes(bytes)?,
Path::Unpadded => self.encrypt_left_unpadded_bytes(bytes)?,
};
Ok(Query::new(left.to_bytes()))
}
fn compare_raw_slices(a: &[u8], b: &[u8]) -> Option<Ordering> {
let (ca, cb) = parse_pair(a, b)?;
if a.len() != total_len(ca) || b.len() != total_len(cb) {
return None;
}
if !symbols_in_domain(a, ca) || !symbols_in_domain(b, cb) {
return None;
}
Some(Self::compare_views(a, ca, b, cb))
}
fn compare_left_to_full(left: &[u8], full: &[u8]) -> Option<Ordering> {
let (cl, cf) = parse_pair(left, full)?;
if left.len() != left_len(cl) || full.len() != total_len(cf) {
return None;
}
if !symbols_in_domain(left, cl) || !symbols_in_domain(full, cf) {
return None;
}
Some(Self::compare_views(left, cl, full, cf))
}
}
impl OreAes128Bit6Chained {
fn compare_views(a: &[u8], ca: usize, b: &[u8], cb: usize) -> Ordering {
let min_count = ca.min(cb);
let mut is_equal = Choice::from(1u8);
let mut diff = FirstDiff::<RIGHT_LEN>::new();
for n in 0..min_count {
let differs = !xt_at(a, n).ct_eq(&xt_at(b, n)) | !f_at(a, ca, n).ct_eq(f_at(b, cb, n));
let first = is_equal & differs;
diff.latch(xt_at(a, n), f_at(a, ca, n), right_at(b, cb, n), first);
is_equal.conditional_assign(&Choice::from(0u8), first);
}
if bool::from(is_equal) {
return ca.cmp(&cb);
}
let hasher = FixedPiZ2Hash::new(HashKey::from_slice(nonce_at(b, cb)));
if diff.resolve(&hasher) == 1 {
Ordering::Greater
} else {
Ordering::Less
}
}
}
impl Drop for OreAes128Bit6Chained {
fn drop(&mut self) {
self.k_acc.zeroize();
}
}
impl ZeroizeOnDrop for OreAes128Bit6Chained {}
fn symbols_in_domain(view: &[u8], count: usize) -> bool {
(0..count).all(|i| usize::from(xt_at(view, i)) < DOMAIN)
}
pub const MAX_STR_BYTES: usize = u16::MAX as usize * 6 / 8;
const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES) <= u16::MAX as usize);
const _: () = assert!(num_blocks_6bit(MAX_STR_BYTES + 1) > u16::MAX as usize);
#[cfg(test)]
fn check_symbols(x: &[u8]) -> Result<Blocks6<&[u8]>, OreError> {
if x.len() > u16::MAX as usize {
return Err(OreError::TooManyBlocks);
}
Blocks6::check(x)
}
#[cfg(test)]
fn str_to_blocks(s: &str, options: &Options) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
padded_bytes_to_blocks(s.as_bytes(), options)
}
fn padded_bytes_to_blocks(
bytes: &[u8],
options: &Options,
) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
if bytes.len() > MAX_STR_BYTES {
return Err(OreError::TooManyBlocks);
}
let padding = options.padding();
let padded = padding.padded_len(bytes.len())?;
if bytes.len() > options.max_bytes().get() {
return Err(OreError::TooLong);
}
if padding != Padding::None {
refuse_trailing_nul(bytes)?;
}
Ok(Blocks6::decompose_padded(
bytes,
Zeroizing::new(vec![0u8; num_blocks_6bit(padded)]),
))
}
fn bytes_to_blocks(bytes: &[u8]) -> Result<Blocks6<Zeroizing<Vec<u8>>>, OreError> {
if bytes.len() > MAX_STR_BYTES {
return Err(OreError::TooManyBlocks);
}
Ok(Blocks6::decompose(
bytes,
Zeroizing::new(vec![0u8; num_blocks_6bit(bytes.len())]),
))
}
#[inline(never)]
fn refuse_trailing_nul(bytes: &[u8]) -> Result<(), OreError> {
if bytes.last() == Some(&0) {
return Err(core::hint::black_box(OreError::TrailingNul));
}
Ok(())
}
#[cfg(kani)]
mod kani_proofs {
use super::*;
#[kani::proof]
fn power_of_two_never_shrinks_and_is_idempotent() {
let min_bytes: u16 = kani::any();
let len: usize = kani::any();
kani::assume(len <= MAX_STR_BYTES);
let padding = Padding::PowerOfTwo { min_bytes };
if let Ok(padded) = padding.padded_len(len) {
assert!(padded >= len);
assert!(padded <= MAX_STR_BYTES);
assert!(padded.is_power_of_two() || padded == usize::from(min_bytes));
assert!(matches!(padding.padded_len(padded), Ok(again) if again == padded));
}
}
#[kani::proof]
fn power_of_two_is_monotone() {
let min_bytes: u16 = kani::any();
let a: usize = kani::any();
let b: usize = kani::any();
kani::assume(a <= b && b <= MAX_STR_BYTES);
let padding = Padding::PowerOfTwo { min_bytes };
if let (Ok(pa), Ok(pb)) = (padding.padded_len(a), padding.padded_len(b)) {
assert!(pa <= pb);
}
}
#[kani::proof]
fn fixed_pads_everything_that_fits() {
let max_bytes: NonZeroU16 = kani::any();
let len: usize = kani::any();
kani::assume(len <= MAX_STR_BYTES);
let padding = Padding::Fixed { max_bytes };
let max_bytes = max_bytes.get();
match padding.padded_len(len) {
Ok(padded) => {
assert!(len <= usize::from(max_bytes) && padded == usize::from(max_bytes))
}
Err(OreError::ExceedsPadding) => assert!(len > usize::from(max_bytes)),
Err(OreError::TooManyBlocks) => assert!(usize::from(max_bytes) > MAX_STR_BYTES),
Err(_) => assert!(false),
}
}
}
#[cfg(test)]
mod compat_vectors;
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::{
bytes_pt, ceiling, fixed_key, fixed_padding, i128_pt, salt, text_pt, u128_pt,
};
fn ore() -> OreAes128Bit6Chained {
OreAes128Bit6Chained::init(fixed_key(0x11)).unwrap()
}
fn ore_with(padding: Padding) -> OreAes128Bit6Chained {
OreAes128Bit6Chained::init_with(fixed_key(0x11), Options::default().with_padding(padding))
.unwrap()
}
fn ore_with_max(padding: Padding, max_bytes: usize) -> OreAes128Bit6Chained {
let options = Options::default()
.with_padding(padding)
.with_max_bytes(ceiling(max_bytes));
OreAes128Bit6Chained::init_with(fixed_key(0x11), options).unwrap()
}
#[test]
fn strings_over_the_ceiling_are_refused() {
type C = OreAes128Bit6Chained;
let c = ore();
assert_eq!(c.options().max_bytes(), DEFAULT_MAX_STR_BYTES);
assert!(c.encrypt_str(&"a".repeat(1024)).is_ok());
assert!(matches!(
c.encrypt_str(&"a".repeat(1025)),
Err(OreError::TooLong)
));
assert!(matches!(
c.encrypt_left_str(&"a".repeat(1025)),
Err(OreError::TooLong)
));
let small = C::init_with(
fixed_key(0x11),
Options::default().with_max_bytes(ceiling(100)),
)
.unwrap();
assert!(small.encrypt_str(&"a".repeat(100)).is_ok());
assert!(matches!(
small.encrypt_str(&"a".repeat(101)),
Err(OreError::TooLong)
));
let unpadded = C::init_with(
fixed_key(0x11),
Options::default()
.with_padding(Padding::None)
.with_max_bytes(ceiling(8)),
)
.unwrap();
assert!(unpadded.encrypt_str("12345678").is_ok());
assert!(matches!(
unpadded.encrypt_str("123456789"),
Err(OreError::TooLong)
));
let fixed = ore_with(fixed_padding(200));
assert_eq!(fixed.options().max_bytes().get(), 200);
assert!(fixed.encrypt_str(&"a".repeat(200)).is_ok());
assert!(matches!(
fixed.encrypt_str(&"a".repeat(201)),
Err(OreError::ExceedsPadding)
));
let fixed_low = C::init_with(
fixed_key(0x11),
Options::default()
.with_padding(fixed_padding(200))
.with_max_bytes(ceiling(50)),
)
.unwrap();
assert_eq!(fixed_low.options().max_bytes().get(), 50);
assert!(matches!(
fixed_low.encrypt_str(&"a".repeat(51)),
Err(OreError::TooLong)
));
assert_eq!(
fixed_low.encrypt_str("abc").unwrap().to_bytes().len(),
total_len(num_blocks_6bit(200))
);
assert!(matches!(
C::init_with(
fixed_key(0x11),
Options::default().with_max_bytes(ceiling(32769))
),
Err(OreError::InitFailed)
));
assert!(C::init_with(
fixed_key(0x11),
Options::default().with_max_bytes(ceiling(32768))
)
.is_ok());
assert!(C::init_with(
fixed_key(0x11),
Options::default()
.with_padding(Padding::None)
.with_max_bytes(ceiling(MAX_STR_BYTES))
)
.is_ok());
assert!(matches!(
C::init_with(
fixed_key(0x11),
Options::default()
.with_padding(Padding::None)
.with_max_bytes(ceiling(MAX_STR_BYTES + 1))
),
Err(OreError::InitFailed)
));
}
const POLICIES: [Padding; 4] = [
Padding::None,
Padding::PowerOfTwo { min_bytes: 16 },
Padding::PowerOfTwo { min_bytes: 0 },
fixed_padding(48),
];
#[test]
fn raw_symbols_are_checked() {
let c = ore();
assert!(matches!(
c.encrypt_var(&[1, 64, 2]),
Err(OreError::PrpError(_))
));
assert!(matches!(
c.encrypt_left_var(&[1, 64, 2]),
Err(OreError::PrpError(_))
));
let unpadded = ore_with(Padding::None);
let blocks =
str_to_blocks("alice", &Options::default().with_padding(Padding::None)).unwrap();
assert_eq!(
unpadded
.encrypt_left_var(blocks.as_bytes())
.unwrap()
.to_bytes(),
unpadded.encrypt_left_str("alice").unwrap().to_bytes()
);
}
#[test]
fn salt_separates_keys() {
type C = OreAes128Bit6Chained;
let plain = C::init(fixed_key(0x42)).unwrap();
let empty = C::init_with_salt(fixed_key(0x42), &Context::empty()).unwrap();
let col_a = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
let col_a2 = C::init_with_salt(fixed_key(0x42), &salt(b"users.email")).unwrap();
let col_b = C::init_with_salt(fixed_key(0x42), &salt(b"users.phone")).unwrap();
let col_a_opts = C::init_with(
fixed_key(0x42),
Options::default().with_salt(&salt(b"users.email")),
)
.unwrap();
assert_eq!(col_a.options().salt(), b"users.email");
let left = |c: &C| c.encrypt_left_str("alice").unwrap().to_bytes();
assert_eq!(left(&plain), left(&empty));
assert_eq!(left(&col_a), left(&col_a2));
assert_eq!(left(&col_a), left(&col_a_opts));
assert_ne!(left(&plain), left(&col_a));
assert_ne!(left(&col_a), left(&col_b));
let a = col_a.encrypt_str("alice").unwrap().to_bytes();
let b = col_b.encrypt_str("alice").unwrap().to_bytes();
assert_ne!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
assert_eq!(
C::compare_raw_slices(&a, &col_a2.encrypt_str("alice").unwrap().to_bytes()),
Some(Ordering::Equal)
);
assert_ne!(
col_a.encrypt_query_plaintext(&u128_pt(7)).unwrap(),
col_b.encrypt_query_plaintext(&u128_pt(7)).unwrap()
);
}
#[test]
fn cross_salt_empty_strings_compare_equal() {
type C = OreAes128Bit6Chained;
let options = Options::default().with_padding(Padding::None);
let a = C::init_with(
fixed_key(0x42),
options.clone().with_salt(&salt(b"users.email")),
)
.unwrap();
let b = C::init_with(fixed_key(0x42), options.with_salt(&salt(b"users.phone"))).unwrap();
let a = a.encrypt_str("").unwrap().to_bytes();
let b = b.encrypt_str("").unwrap().to_bytes();
assert_eq!(C::compare_raw_slices(&a, &b), Some(Ordering::Equal));
}
#[test]
fn strings_over_the_wire_limit_are_rejected() {
let c = ore();
let too_long = "a".repeat(MAX_STR_BYTES + 1);
assert!(matches!(
c.encrypt_str(&too_long),
Err(OreError::TooManyBlocks)
));
assert!(matches!(
c.encrypt_left_str(&too_long),
Err(OreError::TooManyBlocks)
));
}
#[test]
fn raw_symbols_over_the_wire_limit_are_rejected() {
let c = ore();
let too_many = vec![64u8; u16::MAX as usize + 1];
assert!(matches!(
c.encrypt_var(&too_many),
Err(OreError::TooManyBlocks)
));
assert!(matches!(
c.encrypt_left_var(&too_many),
Err(OreError::TooManyBlocks)
));
}
#[test]
fn comparators_reject_out_of_domain_symbols() {
let c = ore();
let a = c.encrypt_str("apple").unwrap().to_bytes();
let b = c.encrypt_str("apricot").unwrap().to_bytes();
let q = c.encrypt_left_str("apple").unwrap().to_bytes();
assert!(OreAes128Bit6Chained::compare_raw_slices(&a, &b).is_some());
let mut bad = a.clone();
bad[HEADER_LEN] = DOMAIN as u8;
let mut bad_q = q.clone();
bad_q[HEADER_LEN] = DOMAIN as u8;
type C = OreAes128Bit6Chained;
assert_eq!(C::compare_raw_slices(&bad, &b), None);
assert_eq!(C::compare_raw_slices(&b, &bad), None);
assert_eq!(C::compare_left_to_full(&bad_q, &b), None);
assert_eq!(C::compare_left_to_full(&q, &bad), None);
}
fn cmp(c: &OreAes128Bit6Chained, a: &str, b: &str) -> Ordering {
let ca = c.encrypt_str(a).unwrap().to_bytes();
let cb = c.encrypt_str(b).unwrap().to_bytes();
OreAes128Bit6Chained::compare_raw_slices(&ca, &cb).unwrap()
}
#[test]
fn string_total_order_matches_lexicographic() {
let words = [
"",
"a",
"a\0b",
"ab",
"abc",
"abd",
"ac",
"b",
"banana",
"bananas",
"sixteen bytes ok",
"sixteen bytes ok!",
"thirty-two bytes, on the nose!!!",
"thirty-two bytes, on the nose!!!!",
"the quick brown fox jumps over the lazy dog",
"the quick brown fox jumps over the lazy dog.",
"zzz",
];
for padding in POLICIES {
let c = ore_with(padding);
for &a in &words {
for &b in &words {
assert_eq!(
cmp(&c, a, b),
a.cmp(b),
"order mismatch for {a:?} vs {b:?} under {padding:?}"
);
}
}
}
}
#[test]
fn power_of_two_lengths() {
let p = |min_bytes, len| Padding::PowerOfTwo { min_bytes }.padded_len(len).unwrap();
for len in 0..=16 {
assert_eq!(p(16, len), 16);
}
assert_eq!(p(16, 17), 32);
assert_eq!(p(16, 32), 32);
assert_eq!(p(16, 33), 64);
assert_eq!(p(16, 1000), 1024);
assert_eq!(p(16, 1025), 2048);
assert_eq!(p(0, 0), 0);
assert_eq!(p(0, 1), 1);
assert_eq!(p(0, 3), 4);
assert_eq!(p(24, 20), 24);
assert_eq!(p(24, 24), 24);
assert_eq!(p(24, 25), 32);
assert_eq!(p(16, 32768), 32768);
for len in [32769, MAX_STR_BYTES] {
assert!(matches!(
Padding::PowerOfTwo { min_bytes: 16 }.padded_len(len),
Err(OreError::TooManyBlocks)
));
}
}
#[test]
fn padded_ciphertexts_reveal_only_the_bucket() {
let c = ore();
let size = |s: &str| c.encrypt_str(s).unwrap().to_bytes().len();
let left_size = |s: &str| c.encrypt_left_str(s).unwrap().to_bytes().len();
for s in ["", "a", "abc", "sixteen bytes ok"] {
assert_eq!(size(s), total_len(num_blocks_6bit(16)), "{s:?}");
assert_eq!(left_size(s), left_len(num_blocks_6bit(16)), "{s:?}");
}
assert_eq!(size("seventeen bytes!!"), total_len(num_blocks_6bit(32)));
assert_eq!(
size("thirty-two bytes, on the nose!!!"),
total_len(num_blocks_6bit(32))
);
assert_eq!(
size("thirty-two bytes, on the nose!!!!"),
total_len(num_blocks_6bit(64))
);
let fixed = ore_with(fixed_padding(48));
for s in ["", "abc", &"x".repeat(48)] {
assert_eq!(
fixed.encrypt_str(s).unwrap().to_bytes().len(),
total_len(num_blocks_6bit(48))
);
}
}
#[test]
fn padded_strings_must_not_end_in_nul() {
for padding in POLICIES {
let c = ore_with(padding);
let full = c.encrypt_str("a\0");
let left = c.encrypt_left_str("a\0");
if padding == Padding::None {
assert_eq!(cmp(&c, "a", "a\0"), Ordering::Less);
} else {
assert!(matches!(full, Err(OreError::TrailingNul)), "{:?}", padding);
assert!(matches!(left, Err(OreError::TrailingNul)), "{:?}", padding);
}
assert!(c.encrypt_str("a\0b").is_ok());
}
}
#[test]
fn fixed_padding_refuses_longer_strings() {
let c = ore_with(fixed_padding(8));
assert!(c.encrypt_str("12345678").is_ok());
assert!(matches!(
c.encrypt_str("123456789"),
Err(OreError::ExceedsPadding)
));
assert!(matches!(
c.encrypt_left_str("123456789"),
Err(OreError::ExceedsPadding)
));
}
#[test]
fn padding_policies_past_the_wire_limit_are_refused() {
type C = OreAes128Bit6Chained;
let max = MAX_STR_BYTES as u16;
let with = |padding| Options::default().with_padding(padding);
assert!(C::init_with(fixed_key(0x11), with(fixed_padding(max))).is_ok());
assert!(matches!(
C::init_with(fixed_key(0x11), with(fixed_padding(max + 1))),
Err(OreError::InitFailed)
));
assert!(C::init_with(
fixed_key(0x11),
with(Padding::PowerOfTwo { min_bytes: max })
)
.is_ok());
assert!(matches!(
C::init_with(
fixed_key(0x11),
with(Padding::PowerOfTwo { min_bytes: max + 1 })
),
Err(OreError::InitFailed)
));
let c = ore_with_max(Padding::default(), 32768);
for len in [32769, MAX_STR_BYTES] {
assert!(matches!(
c.encrypt_str(&"a".repeat(len)),
Err(OreError::TooManyBlocks)
));
}
}
#[test]
fn comparators_refuse_mixed_policies() {
type C = OreAes128Bit6Chained;
for pa in POLICIES {
for pb in POLICIES {
let a = ore_with(pa);
let b = ore_with(pb);
let full_a = a.encrypt_str("abc").unwrap().to_bytes();
let full_b = b.encrypt_str("abc").unwrap().to_bytes();
let left_a = a.encrypt_left_str("abc").unwrap().to_bytes();
let expected = (pa == pb).then_some(Ordering::Equal);
assert_eq!(C::compare_raw_slices(&full_a, &full_b), expected);
assert_eq!(C::compare_left_to_full(&left_a, &full_b), expected);
}
}
}
#[test]
fn padding_tag_round_trips_and_rejects_unknown_kinds() {
let c = ore();
let bytes = c.encrypt_str("abc").unwrap().to_bytes();
let ct = VarCipherText::from_slice(&bytes).unwrap();
assert_eq!(ct.padding(), Padding::default());
assert_eq!(
c.encrypt_left_str("abc").unwrap().padding(),
Padding::default()
);
type C = OreAes128Bit6Chained;
let tag = WIRE_HEADER_LEN;
let tampered = |at: usize, value: u8| {
let mut t = bytes.clone();
t[at] = value;
t
};
for bad in [
tampered(tag, 3), tampered(tag, 0), tampered(tag + 1, 0xff), ] {
assert!(VarCipherText::from_slice(&bad).is_err());
assert_eq!(C::compare_raw_slices(&bad, &bad), None);
}
}
fn small_alphabet_strings() -> Vec<String> {
let mut out = vec![String::new()];
let mut layer = vec![String::new()];
for _ in 0..4 {
layer = layer
.iter()
.flat_map(|s| ["\0", "a", "b"].iter().map(move |c| format!("{s}{c}")))
.collect();
out.extend(layer.iter().cloned());
}
out.retain(|s| !s.ends_with('\0'));
for n in [15, 16, 17, 31, 32, 33] {
out.push("a".repeat(n));
out.push(format!("{}é", "a".repeat(n - 1)));
}
out
}
#[test]
fn small_alphabet_total_order_under_every_policy() {
type C = OreAes128Bit6Chained;
let strings = small_alphabet_strings();
for padding in POLICIES {
let c = ore_with(padding);
let fulls: Vec<Vec<u8>> = strings
.iter()
.map(|s| c.encrypt_str(s).unwrap().to_bytes())
.collect();
let lefts: Vec<Vec<u8>> = strings
.iter()
.map(|s| c.encrypt_left_str(s).unwrap().to_bytes())
.collect();
for (i, a) in strings.iter().enumerate() {
for (j, b) in strings.iter().enumerate() {
let expected = Some(a.as_bytes().cmp(b.as_bytes()));
assert_eq!(
C::compare_raw_slices(&fulls[i], &fulls[j]),
expected,
"full {a:?} vs {b:?} under {padding:?}"
);
assert_eq!(
C::compare_left_to_full(&lefts[i], &fulls[j]),
expected,
"left {a:?} vs {b:?} under {padding:?}"
);
}
}
}
}
#[test]
fn default_buckets_at_every_length() {
type C = OreAes128Bit6Chained;
let c = ore();
let bucket = |n: usize| if n <= 16 { 16 } else { n.next_power_of_two() };
let mut prev: Option<Vec<u8>> = None;
for n in 0..=70 {
let s = "a".repeat(n);
let full = c.encrypt_str(&s).unwrap().to_bytes();
let left = c.encrypt_left_str(&s).unwrap().to_bytes();
assert_eq!(
full.len(),
total_len(num_blocks_6bit(bucket(n))),
"{n} bytes"
);
assert_eq!(
left.len(),
left_len(num_blocks_6bit(bucket(n))),
"{n} bytes"
);
let longer = c.encrypt_str(&format!("{s}b")).unwrap().to_bytes();
assert_eq!(
C::compare_raw_slices(&full, &longer),
Some(Ordering::Less),
"{n} bytes"
);
assert_eq!(
C::compare_left_to_full(&left, &longer),
Some(Ordering::Less),
"{n} bytes"
);
if let Some(prev) = &prev {
assert_eq!(
C::compare_raw_slices(prev, &full),
Some(Ordering::Less),
"{n} bytes"
);
}
prev = Some(full);
}
}
#[test]
fn same_blocks_under_different_policies_do_not_compare() {
type C = OreAes128Bit6Chained;
let cases = [
(
Padding::PowerOfTwo { min_bytes: 16 },
fixed_padding(16),
"sixteen bytes ok",
),
(
Padding::PowerOfTwo { min_bytes: 16 },
Padding::PowerOfTwo { min_bytes: 8 },
"seventeen bytes!!",
),
(
fixed_padding(4),
Padding::PowerOfTwo { min_bytes: 0 },
"abc",
),
];
for (pa, pb, s) in cases {
let (a, b) = (ore_with(pa), ore_with(pb));
let left_a = a.encrypt_left_str(s).unwrap().to_bytes();
let left_b = b.encrypt_left_str(s).unwrap().to_bytes();
assert_eq!(
left_a[..WIRE_HEADER_LEN],
left_b[..WIRE_HEADER_LEN],
"{s:?}"
);
assert_ne!(left_a[..HEADER_LEN], left_b[..HEADER_LEN], "{s:?}");
assert_eq!(left_a[HEADER_LEN..], left_b[HEADER_LEN..], "{s:?}");
let full_b = b.encrypt_str(s).unwrap().to_bytes();
assert_eq!(C::compare_left_to_full(&left_a, &full_b), None, "{s:?}");
let full_a = a.encrypt_str(s).unwrap().to_bytes();
assert_eq!(C::compare_raw_slices(&full_a, &full_b), None, "{s:?}");
}
}
#[test]
#[ignore = "65535-block ciphertexts: about ten seconds unoptimised"]
fn fixed_padding_at_the_wire_limit() {
type C = OreAes128Bit6Chained;
let c = ore_with_max(fixed_padding(MAX_STR_BYTES as u16), MAX_STR_BYTES);
let full = c.encrypt_str("alice").unwrap().to_bytes();
assert_eq!(full.len(), total_len(u16::MAX as usize));
assert_eq!(VarCipherText::from_slice(&full).unwrap().to_bytes(), full);
let left = c.encrypt_left_str("alicf").unwrap().to_bytes();
assert_eq!(left.len(), left_len(u16::MAX as usize));
assert_eq!(
C::compare_left_to_full(&left, &full),
Some(Ordering::Greater)
);
}
#[test]
fn policies_admit_only_their_own_block_counts() {
let blocks = num_blocks_6bit;
let pow16 = Padding::PowerOfTwo { min_bytes: 16 };
for count in [blocks(16), blocks(32), blocks(64), blocks(32768)] {
assert!(pow16.admits_count(count), "{}", count);
}
for count in [0, blocks(8), blocks(16) + 1, blocks(48), blocks(65536)] {
assert!(!pow16.admits_count(count), "{}", count);
}
let pow24 = Padding::PowerOfTwo { min_bytes: 24 };
assert!(pow24.admits_count(blocks(24)));
assert!(pow24.admits_count(blocks(32)));
assert!(!pow24.admits_count(blocks(16)));
let pow0 = Padding::PowerOfTwo { min_bytes: 0 };
for len in [0, 1, 2, 4, 8, 1024] {
assert!(pow0.admits_count(blocks(len)), "{}", len);
}
assert!(!pow0.admits_count(blocks(3)));
let fixed = fixed_padding(48);
assert!(fixed.admits_count(blocks(48)));
assert!(!fixed.admits_count(blocks(48) - 1));
for count in [0, 1, 1000, u16::MAX as usize] {
assert!(Padding::None.admits_count(count));
}
}
#[test]
fn parsers_reject_counts_the_policy_cannot_produce() {
type C = OreAes128Bit6Chained;
let retag = |bytes: &[u8], padding: Padding| {
let mut t = bytes.to_vec();
t[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&padding.to_wire());
t
};
let unpadded = ore_with(Padding::None)
.encrypt_str("abc")
.unwrap()
.to_bytes();
let forged = retag(&unpadded, Padding::default());
assert!(VarCipherText::from_slice(&forged).is_err());
let genuine = ore().encrypt_str("abc").unwrap().to_bytes();
assert_eq!(C::compare_raw_slices(&forged, &genuine), None);
assert_eq!(C::compare_raw_slices(&forged, &forged), None);
let left = retag(
&ore_with(Padding::None)
.encrypt_left_str("abc")
.unwrap()
.to_bytes(),
Padding::default(),
);
assert_eq!(C::compare_left_to_full(&left, &genuine), None);
assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(48))).is_err());
assert!(VarCipherText::from_slice(&retag(&genuine, fixed_padding(16))).is_ok());
let mut empty = ore_with(Padding::None).encrypt_str("").unwrap().to_bytes();
assert!(VarCipherText::from_slice(&empty).is_ok());
empty[WIRE_HEADER_LEN..HEADER_LEN].copy_from_slice(&[2, 0, 0]);
assert!(VarCipherText::from_slice(&empty).is_err());
assert_eq!(C::compare_raw_slices(&empty, &empty), None);
}
#[test]
fn equality_same_plaintext_across_nonces() {
let c = ore();
let a = c.encrypt_str("hello world").unwrap().to_bytes();
let b = c.encrypt_str("hello world").unwrap().to_bytes();
assert_ne!(a, b, "nonces should differ"); assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(&a, &b),
Some(Ordering::Equal)
);
}
#[test]
fn serialize_roundtrip() {
let c = ore();
let ct = c.encrypt_str("roundtrip me").unwrap();
let bytes = ct.to_bytes();
let parsed = VarCipherText::from_slice(&bytes).unwrap();
assert_eq!(parsed.to_bytes(), bytes);
}
#[test]
fn beyond_packed_cap() {
let c = ore();
let long_a = "aaaaaaaaaaaaaaaaaaaaaaaa"; let long_b = "aaaaaaaaaaaaaaaaaaaaaaab";
assert_eq!(cmp(&c, long_a, long_b), Ordering::Less);
assert_eq!(cmp(&c, long_a, long_a), Ordering::Equal);
}
#[test]
fn fixed_width_plaintexts_are_unpadded_terms() {
let c = ore();
let n = c.encrypt_plaintext(&u128_pt(7)).unwrap();
let n_left = c.encrypt_query_plaintext(&u128_pt(7)).unwrap();
assert_eq!(n.as_bytes().len(), total_len(22));
assert_eq!(n_left.as_bytes().len(), left_len(22));
assert_eq!(
parse_chained_header(n.as_bytes()),
Some((22, Padding::None))
);
assert_eq!(
n_left.as_bytes(),
c.encrypt_left_unpadded_bytes(&7u128.to_be_bytes())
.unwrap()
.to_bytes()
);
assert_eq!(
OreAes128Bit6Chained::compare_left_to_full(n_left.as_bytes(), n.as_bytes()),
Some(Ordering::Equal)
);
let s16_padded = c.encrypt_str("0123456789abcdef").unwrap().to_bytes();
let s16 = ore_with(Padding::None)
.encrypt_str("0123456789abcdef")
.unwrap()
.to_bytes();
assert_eq!(
parse_chained_header(&s16_padded).map(|(count, _)| count),
Some(22)
);
assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16_padded),
None
);
assert!(OreAes128Bit6Chained::compare_raw_slices(n.as_bytes(), &s16).is_some());
}
#[test]
fn only_text_is_padded() {
let c = ore();
let text = c.encrypt_plaintext(&text_pt("alice")).unwrap();
assert_eq!(
parse_chained_header(text.as_bytes()),
Some((num_blocks_6bit(16), Padding::default()))
);
let bytes = c.encrypt_plaintext(&bytes_pt(b"alice")).unwrap();
assert_eq!(
parse_chained_header(bytes.as_bytes()),
Some((num_blocks_6bit(6), Padding::None))
);
let n = c.encrypt_plaintext(&i128_pt(-1)).unwrap();
assert_eq!(
parse_chained_header(n.as_bytes()),
Some((22, Padding::None))
);
assert!(c.encrypt_plaintext(&bytes_pt(b"\0")).is_ok());
let small = ore_with_max(Padding::None, 8);
assert!(small.encrypt_plaintext(&text_pt("1234567")).is_ok());
assert!(matches!(
small.encrypt_plaintext(&text_pt("12345678")),
Err(OreError::TooLong)
));
assert!(small.encrypt_plaintext(&bytes_pt(&[0u8; 7])).is_ok());
assert!(matches!(
small.encrypt_plaintext(&bytes_pt(&[0u8; 8])),
Err(OreError::TooLong)
));
assert!(matches!(
small.encrypt_query_plaintext(&bytes_pt(&[0u8; 8])),
Err(OreError::TooLong)
));
assert!(small.encrypt_plaintext(&u128_pt(u128::MAX)).is_ok());
}
#[test]
fn unpadded_bytes_past_the_wire_limit_are_refused_by_length() {
let c = ore();
let too_wide = vec![0u8; MAX_STR_BYTES + 1];
assert!(matches!(
c.encrypt_unpadded_bytes(&too_wide),
Err(OreError::TooManyBlocks)
));
assert!(matches!(
c.encrypt_left_unpadded_bytes(&too_wide),
Err(OreError::TooManyBlocks)
));
assert!(c
.encrypt_left_unpadded_bytes(&too_wide[..MAX_STR_BYTES])
.is_ok());
}
#[test]
fn signed_128_orders_across_zero() {
let c = ore();
let vals = [i128::MIN, -1, 0, 1, i128::MAX];
let cts: Vec<Vec<u8>> = vals
.iter()
.map(|&v| c.encrypt_plaintext(&i128_pt(v)).unwrap().into_bytes())
.collect();
for (i, a) in cts.iter().enumerate() {
for (j, b) in cts.iter().enumerate() {
assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(a, b),
Some(vals[i].cmp(&vals[j])),
"{} vs {}",
vals[i],
vals[j]
);
}
}
}
#[test]
fn cross_scheme_bytes_rejected() {
let c = ore();
let mut bytes = c.encrypt_str("x").unwrap().to_bytes();
bytes[1] = 0x02; assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(&bytes, &bytes),
None
);
}
#[test]
fn left_query_path_and_artifact_rejection() {
let c = ore();
let left = c.encrypt_left_str("hi").unwrap().to_bytes();
let full = c.encrypt_str("hi").unwrap().to_bytes();
assert_eq!(
OreAes128Bit6Chained::compare_left_to_full(&left, &full),
Some(Ordering::Equal)
);
assert_eq!(OreAes128Bit6Chained::compare_raw_slices(&left, &full), None);
assert_eq!(
OreAes128Bit6Chained::compare_left_to_full(&full, &full),
None
);
}
#[test]
fn empty_string_sorts_first() {
let c = ore();
assert_eq!(cmp(&c, "", "a"), Ordering::Less);
assert_eq!(cmp(&c, "", ""), Ordering::Equal);
}
const PROP_MAX_BLOCKS: usize = 32;
fn to_domain(v: &[u8]) -> Vec<u8> {
v.iter().take(PROP_MAX_BLOCKS).map(|b| b & 0x3f).collect()
}
fn enc(c: &OreAes128Bit6Chained, x: &[u8]) -> Vec<u8> {
c.encrypt_var(x).unwrap().to_bytes()
}
quickcheck! {
fn prop_block_order_matches_lex(a: Vec<u8>, b: Vec<u8>) -> bool {
let c = ore();
let (a, b) = (to_domain(&a), to_domain(&b));
let (ea, eb) = (enc(&c, &a), enc(&c, &b));
OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
}
fn prop_left_query_matches_full(a: Vec<u8>, b: Vec<u8>) -> bool {
let c = ore();
let (a, b) = (to_domain(&a), to_domain(&b));
let left_a = c.encrypt_left_var(&a).unwrap().to_bytes();
let full_b = enc(&c, &b);
OreAes128Bit6Chained::compare_left_to_full(&left_a, &full_b)
== Some(a.cmp(&b))
}
fn prop_shared_prefix_order(prefix: Vec<u8>, sa: Vec<u8>, sb: Vec<u8>) -> bool {
let c = ore();
let p = to_domain(&prefix);
let mut a = p.clone();
a.extend(to_domain(&sa));
a.truncate(PROP_MAX_BLOCKS);
let mut b = p;
b.extend(to_domain(&sb));
b.truncate(PROP_MAX_BLOCKS);
let (ea, eb) = (enc(&c, &a), enc(&c, &b));
OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(&b))
}
fn prop_string_order_matches_str(a: String, b: String) -> bool {
let a: String = a.chars().take(12).collect();
let b: String = b.chars().take(12).collect();
let (a, b) = (a.trim_end_matches('\0'), b.trim_end_matches('\0'));
POLICIES.iter().all(|&padding| {
let c = ore_with(padding);
let ea = c.encrypt_str(a).unwrap().to_bytes();
let eb = c.encrypt_str(b).unwrap().to_bytes();
OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
})
}
fn prop_padded_prefix_order(prefix: String, tail: String) -> bool {
let a: String = prefix.chars().take(20).collect();
let a = a.trim_end_matches('\0');
let b: String = a.chars().chain(tail.chars().take(8)).collect();
let b = b.trim_end_matches('\0');
POLICIES[1..3].iter().all(|&padding| {
let c = ore_with(padding);
let ea = c.encrypt_str(a).unwrap().to_bytes();
let eb = c.encrypt_str(b).unwrap().to_bytes();
OreAes128Bit6Chained::compare_raw_slices(&ea, &eb) == Some(a.cmp(b))
})
}
fn prop_power_of_two_buckets(a: u16, b: u16) -> bool {
let (a, b) = (usize::from(a) / 2, usize::from(b) / 2);
let p = |n| Padding::PowerOfTwo { min_bytes: 0 }.padded_len(n).unwrap();
let pa = p(a);
pa >= a && pa < 2 * a.max(1) && (a > b || pa <= p(b)) && p(pa) == pa
}
fn prop_padding_is_nul_extension(s: String) -> bool {
let s: String = s.chars().take(40).collect();
let s = s.trim_end_matches('\0');
let unpadded = ore_with(Padding::None);
POLICIES.iter().all(|&padding| {
let c = ore_with(padding);
let Ok(padded) = padding.padded_len(s.len()) else {
return matches!(padding, Padding::Fixed { .. })
&& matches!(c.encrypt_left_str(s), Err(OreError::ExceedsPadding))
&& matches!(c.encrypt_str(s), Err(OreError::ExceedsPadding));
};
let mut extended = s.to_owned();
extended.extend(std::iter::repeat_n('\0', padded - s.len()));
let left = c.encrypt_left_str(s).unwrap();
let a = left.to_bytes();
let b = unpadded.encrypt_left_str(&extended).unwrap().to_bytes();
left.padding() == padding
&& a[..WIRE_HEADER_LEN] == b[..WIRE_HEADER_LEN]
&& a[HEADER_LEN..] == b[HEADER_LEN..]
})
}
fn prop_string_equality_under_every_policy(s: String) -> bool {
type C = OreAes128Bit6Chained;
let s: String = s.chars().take(12).collect();
let s = s.trim_end_matches('\0');
POLICIES.iter().all(|&padding| {
let c = ore_with(padding);
let a = c.encrypt_str(s).unwrap().to_bytes();
let b = c.encrypt_str(s).unwrap().to_bytes();
let l = c.encrypt_left_str(s).unwrap().to_bytes();
C::compare_raw_slices(&a, &b) == Some(Ordering::Equal)
&& C::compare_left_to_full(&l, &b) == Some(Ordering::Equal)
&& VarCipherText::from_slice(&a)
.map(|ct| ct.to_bytes() == a && ct.padding() == padding)
.unwrap_or(false)
})
}
fn prop_padding_refuses_exactly_trailing_nul(s: String, nul: bool) -> bool {
let mut s: String = s.chars().take(11).collect();
if nul {
s.push('\0');
}
let ends_in_nul = s.ends_with('\0');
POLICIES.iter().all(|&padding| {
let c = ore_with(padding);
let (full, left) = (c.encrypt_str(&s), c.encrypt_left_str(&s));
if padding != Padding::None && ends_in_nul {
matches!(full, Err(OreError::TrailingNul))
&& matches!(left, Err(OreError::TrailingNul))
} else {
full.is_ok() && left.is_ok()
}
})
}
fn prop_parsers_never_panic(bytes: Vec<u8>, at: usize, value: u8) -> bool {
type C = OreAes128Bit6Chained;
let good = ore().encrypt_str("alice").unwrap().to_bytes();
let mut changed = good.clone();
changed[at % good.len()] = value;
for x in [&bytes, &changed] {
let _ = VarCipherText::from_slice(x);
let _ = C::compare_raw_slices(x, x);
let _ = C::compare_raw_slices(x, &good);
let _ = C::compare_left_to_full(x, &good);
let _ = C::compare_left_to_full(&good, x);
}
true
}
fn prop_u128_order(a: u128, b: u128) -> bool {
let c = ore();
let ca = c.encrypt_plaintext(&u128_pt(a)).unwrap();
let cb = c.encrypt_plaintext(&u128_pt(b)).unwrap();
let la = c.encrypt_query_plaintext(&u128_pt(a)).unwrap();
OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
&& OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
}
fn prop_i128_order(a: i128, b: i128) -> bool {
let c = ore();
let ca = c.encrypt_plaintext(&i128_pt(a)).unwrap();
let cb = c.encrypt_plaintext(&i128_pt(b)).unwrap();
let la = c.encrypt_query_plaintext(&i128_pt(a)).unwrap();
OreAes128Bit6Chained::compare_raw_slices(ca.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
&& OreAes128Bit6Chained::compare_left_to_full(la.as_bytes(), cb.as_bytes()) == Some(a.cmp(&b))
}
fn prop_equality_across_nonces(x: Vec<u8>) -> bool {
let c = ore();
let x = to_domain(&x);
let (a, b) = (enc(&c, &x), enc(&c, &x));
let equal = OreAes128Bit6Chained::compare_raw_slices(&a, &b)
== Some(Ordering::Equal);
let distinct = x.is_empty() || a != b;
equal && distinct
}
fn prop_left_deterministic_and_consistent(x: Vec<u8>) -> bool {
let c = ore();
let x = to_domain(&x);
let l1 = c.encrypt_left_var(&x).unwrap().to_bytes();
let l2 = c.encrypt_left_var(&x).unwrap().to_bytes();
let full = c.encrypt_var(&x).unwrap();
l1 == l2 && full.left.to_bytes() == l1
}
fn prop_serialize_roundtrip(x: Vec<u8>) -> bool {
let c = ore();
let x = to_domain(&x);
let bytes = enc(&c, &x);
match VarCipherText::from_slice(&bytes) {
Ok(ct) => ct.to_bytes() == bytes,
Err(_) => false,
}
}
}
fn block_tables(ore: &OreAes128Bit6Chained, s: &str) -> Vec<Vec<u8>> {
let blocks = str_to_blocks(s, &ore.options).unwrap();
let mut acc = CmacAccumulator::new(&ore.k_acc);
let mut needles = Vec::new();
for (n, &sym) in blocks.as_bytes().iter().enumerate() {
let prp = ore.prp_at(&acc, n as u16);
let symbols = (0..64).map(crate::primitives::Symbol::<64>::from_low_bits);
needles.push(symbols.clone().map(|i| prp.permute(i).get()).collect());
needles.push(symbols.map(|i| prp.invert(i).get()).collect());
acc.absorb(&prefix_block(n as u16, sym));
}
needles
}
fn assert_no_block_tables(
encrypt: fn(&OreAes128Bit6Chained, &str),
unscrubbed: fn(&OreAes128Bit6Chained, &str),
) {
use crate::primitives::stack::{residue, SCRUB_BYTES};
const S: &str = "a chained residue test string";
let needles = block_tables(&ore(), S);
let dead = residue::after(move || unscrubbed(&ore(), S));
assert!(needles.iter().any(|n| residue::contains(&dead, n)));
let depth = residue::depth(&dead);
assert!(
depth < SCRUB_BYTES,
"encryption reached {} bytes of stack, past the {}-byte scrub",
depth,
SCRUB_BYTES
);
let dead = residue::after(move || encrypt(&ore(), S));
for (i, needle) in needles.iter().enumerate() {
assert!(
!residue::contains(&dead, needle),
"block {} {} left in dead stack",
i / 2,
["permutation", "inverse"][i % 2]
);
}
}
#[test]
fn encrypt_str_leaves_no_prp_tables_on_the_stack() {
assert_no_block_tables(
|ore, s| {
core::hint::black_box(ore.encrypt_str(s).unwrap());
},
|ore, s| {
let blocks = str_to_blocks(s, &ore.options).unwrap();
core::hint::black_box(ore.encrypt_blocks(&blocks, ore.padding()).unwrap());
},
);
}
fn assert_no_large_plaintext(encrypt: fn(&OreAes128Bit6Chained, &OrderPlaintext)) {
use crate::primitives::stack::{residue, SCRUB_BYTES};
const LEN: usize = MAX_STR_BYTES - 1;
fn raw() -> Vec<u8> {
(0..LEN).map(|i| (i * 37 + 11) as u8).collect()
}
let p = raw();
let needles: Vec<Vec<u8>> = [0, LEN / 2, LEN - 64]
.iter()
.map(|&at| p[at..at + 64].to_vec())
.collect();
if LEN > SCRUB_BYTES {
let dead = residue::after(|| {
let p = raw();
stack::scrubbed(|| {
let mut copy = [0u8; LEN];
copy.copy_from_slice(&p);
core::hint::black_box(©);
});
});
assert!(needles.iter().any(|n| residue::contains(&dead, n)));
}
let dead = residue::after(move || {
encrypt(
&ore_with_max(Padding::None, MAX_STR_BYTES),
&bytes_pt(&raw()),
)
});
for needle in &needles {
assert!(
!residue::contains(&dead, needle),
"plaintext left in dead stack"
);
}
}
#[test]
fn encrypt_plaintext_leaves_no_large_array_on_the_stack() {
assert_no_large_plaintext(|ore, p| {
core::hint::black_box(ore.encrypt_plaintext(p).unwrap());
});
}
#[test]
fn encrypt_query_plaintext_leaves_no_large_array_on_the_stack() {
assert_no_large_plaintext(|ore, p| {
core::hint::black_box(ore.encrypt_query_plaintext(p).unwrap());
});
}
#[test]
fn encrypt_left_str_leaves_no_prp_tables_on_the_stack() {
assert_no_block_tables(
|ore, s| {
core::hint::black_box(ore.encrypt_left_str(s).unwrap());
},
|ore, s| {
let blocks = str_to_blocks(s, &ore.options).unwrap();
core::hint::black_box(ore.encrypt_left_blocks(&blocks, ore.padding()).unwrap());
},
);
}
#[test]
fn every_term_draws_a_fresh_nonce() {
let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
ore.encrypt_plaintext(p).unwrap().into_bytes()
};
let a = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
let b = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
let (a1, a2, b1) = (
term_bytes(&a, &text_pt("alice")),
term_bytes(&a, &text_pt("alice")),
term_bytes(&b, &text_pt("alice")),
);
assert_ne!(a1, a2, "one cipher reused a nonce");
assert_ne!(a1, b1, "two ciphers drew the same nonce stream");
assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(&a1, &b1),
Some(Ordering::Equal)
);
}
#[test]
fn a_poisoned_nonce_lock_still_encrypts() {
let term_bytes = |ore: &OreAes128Bit6Chained, p: &OrderPlaintext| {
ore.encrypt_plaintext(p).unwrap().into_bytes()
};
let ore = OreAes128Bit6Chained::init_with(fixed_key(1), Options::default()).unwrap();
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = ore.rng.lock().unwrap();
panic!("poison the nonce lock");
}));
assert!(ore.rng.is_poisoned());
let (a, b) = (
term_bytes(&ore, &text_pt("alice")),
term_bytes(&ore, &text_pt("alice")),
);
assert_ne!(a, b, "a poisoned lock reused a nonce");
assert_eq!(
OreAes128Bit6Chained::compare_raw_slices(&a, &b),
Some(Ordering::Equal)
);
}
}