use std::cell::RefCell;
use std::cmp::Ordering;
use std::convert::{TryFrom, TryInto};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use subtle_ng::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::{Zeroize, Zeroizing};
use orderable_bytes::FixedOrderableBytes;
use crate::ciphertext::{parse_header, OreOutput, ParseError, 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::{OreEncrypt, OreError};
const VERSION: u8 = 0x02;
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: u16,
},
}
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.into() => max_bytes.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),
};
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: 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.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: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
salt: Vec<u8>,
padding: Padding,
max_bytes: usize,
}
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: &[u8]) -> Self {
Self {
salt: salt.to_vec(),
..self
}
}
pub fn with_padding(self, padding: Padding) -> Self {
Self { padding, ..self }
}
pub fn with_max_bytes(self, max_bytes: usize) -> Self {
Self { max_bytes, ..self }
}
pub fn salt(&self) -> &[u8] {
&self.salt
}
pub fn padding(&self) -> Padding {
self.padding
}
pub fn max_bytes(&self) -> usize {
self.ceiling()
}
fn ceiling(&self) -> usize {
match self.padding {
Padding::Fixed { max_bytes } => self.max_bytes.min(usize::from(max_bytes)),
_ => self.max_bytes,
}
}
fn check(&self) -> Result<(), OreError> {
if self.max_bytes == 0 {
return Err(OreError::InitFailed);
}
self.padding
.padded_len(0)
.map_err(|_| OreError::InitFailed)?;
self.padding
.padded_len(self.ceiling())
.map_err(|_| OreError::InitFailed)?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct VarLeft {
xt: Vec<u8>,
f: Vec<[u8; F_LEN]>,
padding: Padding,
}
#[derive(Clone, Debug)]
pub struct VarRight {
nonce: [u8; NONCE_LEN],
blocks: Vec<[u8; RIGHT_LEN]>,
}
#[derive(Clone, Debug)]
pub 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
}
pub fn padding(&self) -> Padding {
self.padding
}
pub fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
let (count, padding) = parse_chained_header(data).ok_or(ParseError)?;
if data.len() != left_len(count) {
return Err(ParseError);
}
if !symbols_in_domain(data, count) {
return Err(ParseError);
}
Ok(parse_left_view(data, count, padding))
}
}
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
}
pub fn padding(&self) -> Padding {
self.left.padding
}
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<R: Rng + SeedableRng> {
k_acc: [u8; 16],
options: Options,
rng: RefCell<R>,
}
pub type OreAes128Bit6ChainedChaCha20 = OreAes128Bit6Chained<ChaCha20Rng>;
impl<R: Rng + SeedableRng> OreAes128Bit6Chained<R> {
pub fn init(key: &[u8; 16]) -> Result<Self, OreError> {
Self::init_with(key, Options::default())
}
pub fn init_with_salt(key: &[u8; 16], salt: &[u8]) -> Result<Self, OreError> {
Self::init_with(key, Options::default().with_salt(salt))
}
pub fn init_with(key: &[u8; 16], options: Options) -> Result<Self, OreError> {
options.check()?;
let k_salt = keys::salted(&keys::root(key, &ROOT_LABEL), options.salt());
let k_acc = *keys::subkey(&k_salt, &ACC_KEY_LABEL);
Ok(Self {
k_acc,
options,
rng: RefCell::new(R::from_entropy()),
})
}
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.rng.borrow_mut().try_fill(&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 })
}
pub fn encrypt_str(&self, s: &str) -> Result<VarCipherText, OreError> {
stack::scrubbed(|| self.encrypt_blocks(&str_to_blocks(s, &self.options)?, self.padding()))
}
pub fn encrypt_left_str(&self, s: &str) -> Result<VarLeft, OreError> {
stack::scrubbed(|| {
self.encrypt_left_blocks(&str_to_blocks(s, &self.options)?, self.padding())
})
}
pub fn encrypt_fixed<T: FixedOrderableBytes>(&self, x: &T) -> Result<VarCipherText, OreError> {
check_fixed_len::<T>()?;
stack::scrubbed(|| {
let bytes = x.to_orderable_bytes();
self.encrypt_blocks(&bytes_to_blocks(bytes.as_ref())?, Padding::None)
})
}
pub fn encrypt_left_fixed<T: FixedOrderableBytes>(&self, x: &T) -> Result<VarLeft, OreError> {
check_fixed_len::<T>()?;
stack::scrubbed(|| {
let bytes = x.to_orderable_bytes();
self.encrypt_left_blocks(&bytes_to_blocks(bytes.as_ref())?, Padding::None)
})
}
#[cfg(feature = "vitaminc")]
pub(crate) fn encrypt_bytes(&self, bytes: &[u8]) -> Result<VarCipherText, OreError> {
stack::scrubbed(|| {
self.encrypt_blocks(
&padded_bytes_to_blocks(bytes, &self.options)?,
self.padding(),
)
})
}
pub 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))
}
pub 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))
}
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<R: Rng + SeedableRng> Drop for OreAes128Bit6Chained<R> {
fn drop(&mut self) {
self.k_acc.zeroize();
}
}
fn symbols_in_domain(view: &[u8], count: usize) -> bool {
(0..count).all(|i| usize::from(xt_at(view, i)) < DOMAIN)
}
fn unpadded_count(view: &[u8]) -> Option<usize> {
let (count, padding) = parse_chained_header(view)?;
(padding == Padding::None).then_some(count)
}
#[derive(Clone, Debug)]
pub struct ChainedLeft<const BLOCKS: usize>(VarLeft);
#[derive(Clone, Debug)]
pub struct ChainedCipherText<const BLOCKS: usize>(VarCipherText);
impl<const BLOCKS: usize> ChainedLeft<BLOCKS> {
pub fn as_var(&self) -> &VarLeft {
&self.0
}
pub fn into_var(self) -> VarLeft {
self.0
}
}
impl<const BLOCKS: usize> ChainedCipherText<BLOCKS> {
pub fn as_var(&self) -> &VarCipherText {
&self.0
}
pub fn into_var(self) -> VarCipherText {
self.0
}
pub fn compare_raw_slices(a: &[u8], b: &[u8]) -> Option<Ordering> {
if unpadded_count(a)? != BLOCKS || unpadded_count(b)? != BLOCKS {
return None;
}
OreAes128Bit6ChainedChaCha20::compare_raw_slices(a, b)
}
pub fn compare_left_to_full(left: &[u8], full: &[u8]) -> Option<Ordering> {
if unpadded_count(left)? != BLOCKS || unpadded_count(full)? != BLOCKS {
return None;
}
OreAes128Bit6ChainedChaCha20::compare_left_to_full(left, full)
}
}
impl<const BLOCKS: usize> From<ChainedLeft<BLOCKS>> for VarLeft {
fn from(left: ChainedLeft<BLOCKS>) -> Self {
left.0
}
}
impl<const BLOCKS: usize> From<ChainedCipherText<BLOCKS>> for VarCipherText {
fn from(ct: ChainedCipherText<BLOCKS>) -> Self {
ct.0
}
}
impl<const BLOCKS: usize> TryFrom<VarLeft> for ChainedLeft<BLOCKS> {
type Error = ParseError;
fn try_from(left: VarLeft) -> Result<Self, ParseError> {
if left.xt.len() != BLOCKS || left.padding != Padding::None {
return Err(ParseError);
}
Ok(Self(left))
}
}
impl<const BLOCKS: usize> TryFrom<VarCipherText> for ChainedCipherText<BLOCKS> {
type Error = ParseError;
fn try_from(ct: VarCipherText) -> Result<Self, ParseError> {
if ct.left.xt.len() != BLOCKS || ct.left.padding != Padding::None {
return Err(ParseError);
}
Ok(Self(ct))
}
}
impl<const BLOCKS: usize> OreOutput for ChainedLeft<BLOCKS> {
fn size() -> usize {
left_len(BLOCKS)
}
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
VarLeft::from_slice(data)?.try_into()
}
}
impl<const BLOCKS: usize> OreOutput for ChainedCipherText<BLOCKS> {
fn size() -> usize {
total_len(BLOCKS)
}
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes()
}
fn from_slice(data: &[u8]) -> Result<Self, ParseError> {
VarCipherText::from_slice(data)?.try_into()
}
}
macro_rules! impl_ore_encrypt_chained {
($type:ty, $blocks_const:ident, $tests:ident, $lo:expr, $hi:expr) => {
pub const $blocks_const: usize =
num_blocks_6bit(<$type as FixedOrderableBytes>::ENCODED_LEN);
impl<R: Rng + SeedableRng> OreEncrypt<OreAes128Bit6Chained<R>> for $type {
type LeftOutput = ChainedLeft<$blocks_const>;
type FullOutput = ChainedCipherText<$blocks_const>;
fn encrypt_left(
&self,
cipher: &OreAes128Bit6Chained<R>,
) -> Result<Self::LeftOutput, OreError> {
cipher.encrypt_left_fixed(self).map(ChainedLeft)
}
fn encrypt(
&self,
cipher: &OreAes128Bit6Chained<R>,
) -> Result<Self::FullOutput, OreError> {
cipher.encrypt_fixed(self).map(ChainedCipherText)
}
}
#[cfg(test)]
mod $tests {
use super::*;
#[test]
fn round_trip_order_and_equality() {
let ore = OreAes128Bit6ChainedChaCha20::init(&[0x11; 16]).unwrap();
let (lo, hi): ($type, $type) = ($lo, $hi);
assert!(lo < hi);
let lo_ct = lo.encrypt(&ore).unwrap();
let hi_ct = hi.encrypt(&ore).unwrap();
let lo_left = lo.encrypt_left(&ore).unwrap();
let lo_ct2 = lo.encrypt(&ore).unwrap();
let lo_bytes = lo_ct.to_bytes();
let hi_bytes = hi_ct.to_bytes();
assert_eq!(lo_bytes.len(), ChainedCipherText::<$blocks_const>::size());
assert_eq!(
lo_left.to_bytes().len(),
ChainedLeft::<$blocks_const>::size()
);
assert_eq!(
ChainedCipherText::<$blocks_const>::from_slice(&lo_bytes)
.unwrap()
.to_bytes(),
lo_bytes
);
assert_eq!(
ChainedLeft::<$blocks_const>::from_slice(&lo_left.to_bytes())
.unwrap()
.to_bytes(),
lo_left.to_bytes()
);
let cmp = ChainedCipherText::<$blocks_const>::compare_raw_slices;
assert_eq!(cmp(&lo_bytes, &hi_bytes), Some(Ordering::Less));
assert_eq!(cmp(&hi_bytes, &lo_bytes), Some(Ordering::Greater));
assert_ne!(lo_bytes, lo_ct2.to_bytes());
assert_eq!(cmp(&lo_bytes, &lo_ct2.to_bytes()), Some(Ordering::Equal));
assert_eq!(
ChainedCipherText::<$blocks_const>::compare_left_to_full(
&lo_left.to_bytes(),
&hi_bytes
),
Some(Ordering::Less)
);
}
}
};
}
impl_ore_encrypt_chained!(u128, U128_BLOCKS, u128_tests, 0u128, u128::MAX);
impl_ore_encrypt_chained!(i128, I128_BLOCKS, i128_tests, i128::MIN, i128::MAX);
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);
fn check_fixed_len<T: FixedOrderableBytes>() -> Result<(), OreError> {
if T::ENCODED_LEN > MAX_STR_BYTES {
return Err(OreError::TooManyBlocks);
}
Ok(())
}
#[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)
}
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() {
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: u16 = kani::any();
let len: usize = kani::any();
kani::assume(len <= MAX_STR_BYTES);
let padding = Padding::Fixed { max_bytes };
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 tests {
use super::*;
fn ore() -> OreAes128Bit6ChainedChaCha20 {
OreAes128Bit6Chained::init(&[0x11; 16]).unwrap()
}
fn ore_with(padding: Padding) -> OreAes128Bit6ChainedChaCha20 {
OreAes128Bit6Chained::init_with(&[0x11; 16], Options::default().with_padding(padding))
.unwrap()
}
fn ore_with_max(padding: Padding, max_bytes: usize) -> OreAes128Bit6ChainedChaCha20 {
let options = Options::default()
.with_padding(padding)
.with_max_bytes(max_bytes);
OreAes128Bit6Chained::init_with(&[0x11; 16], options).unwrap()
}
#[test]
fn strings_over_the_ceiling_are_refused() {
type C = OreAes128Bit6ChainedChaCha20;
let k = [0x11; 16];
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(&k, Options::default().with_max_bytes(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(
&k,
Options::default()
.with_padding(Padding::None)
.with_max_bytes(8),
)
.unwrap();
assert!(unpadded.encrypt_str("12345678").is_ok());
assert!(matches!(
unpadded.encrypt_str("123456789"),
Err(OreError::TooLong)
));
let fixed = ore_with(Padding::Fixed { max_bytes: 200 });
assert_eq!(fixed.options().max_bytes(), 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(
&k,
Options::default()
.with_padding(Padding::Fixed { max_bytes: 200 })
.with_max_bytes(50),
)
.unwrap();
assert_eq!(fixed_low.options().max_bytes(), 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(&k, Options::default().with_max_bytes(0)),
Err(OreError::InitFailed)
));
assert!(matches!(
C::init_with(&k, Options::default().with_max_bytes(32769)),
Err(OreError::InitFailed)
));
assert!(C::init_with(&k, Options::default().with_max_bytes(32768)).is_ok());
assert!(C::init_with(
&k,
Options::default()
.with_padding(Padding::None)
.with_max_bytes(MAX_STR_BYTES)
)
.is_ok());
assert!(matches!(
C::init_with(
&k,
Options::default()
.with_padding(Padding::None)
.with_max_bytes(MAX_STR_BYTES + 1)
),
Err(OreError::InitFailed)
));
}
const POLICIES: [Padding; 4] = [
Padding::None,
Padding::PowerOfTwo { min_bytes: 16 },
Padding::PowerOfTwo { min_bytes: 0 },
Padding::Fixed { max_bytes: 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 = OreAes128Bit6ChainedChaCha20;
let key = [0x42u8; 16];
let plain = C::init(&key).unwrap();
let empty = C::init_with_salt(&key, &[]).unwrap();
let col_a = C::init_with_salt(&key, b"users.email").unwrap();
let col_a2 = C::init_with_salt(&key, b"users.email").unwrap();
let col_b = C::init_with_salt(&key, b"users.phone").unwrap();
let col_a_opts = C::init_with(&key, Options::default().with_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!(
7u128.encrypt_left(&col_a).unwrap().to_bytes(),
7u128.encrypt_left(&col_b).unwrap().to_bytes()
);
}
#[test]
fn cross_salt_empty_strings_compare_equal() {
type C = OreAes128Bit6ChainedChaCha20;
let key = [0x42u8; 16];
let options = Options::default().with_padding(Padding::None);
let a = C::init_with(&key, options.clone().with_salt(b"users.email")).unwrap();
let b = C::init_with(&key, options.with_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::<ChaCha20Rng>::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<ChaCha20Rng>;
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: &OreAes128Bit6ChainedChaCha20, a: &str, b: &str) -> Ordering {
let ca = c.encrypt_str(a).unwrap().to_bytes();
let cb = c.encrypt_str(b).unwrap().to_bytes();
OreAes128Bit6ChainedChaCha20::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(Padding::Fixed { max_bytes: 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(Padding::Fixed { max_bytes: 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() {
let k = [0x11; 16];
type C = OreAes128Bit6ChainedChaCha20;
let max = MAX_STR_BYTES as u16;
let with = |padding| Options::default().with_padding(padding);
assert!(C::init_with(&k, with(Padding::Fixed { max_bytes: max })).is_ok());
assert!(matches!(
C::init_with(&k, with(Padding::Fixed { max_bytes: max + 1 })),
Err(OreError::InitFailed)
));
assert!(C::init_with(&k, with(Padding::PowerOfTwo { min_bytes: max })).is_ok());
assert!(matches!(
C::init_with(&k, 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 = OreAes128Bit6ChainedChaCha20;
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 = OreAes128Bit6ChainedChaCha20;
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 = OreAes128Bit6ChainedChaCha20;
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 = OreAes128Bit6ChainedChaCha20;
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 = OreAes128Bit6ChainedChaCha20;
let cases = [
(
Padding::PowerOfTwo { min_bytes: 16 },
Padding::Fixed { max_bytes: 16 },
"sixteen bytes ok",
),
(
Padding::PowerOfTwo { min_bytes: 16 },
Padding::PowerOfTwo { min_bytes: 8 },
"seventeen bytes!!",
),
(
Padding::Fixed { max_bytes: 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 = OreAes128Bit6ChainedChaCha20;
let c = ore_with_max(
Padding::Fixed {
max_bytes: 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 = Padding::Fixed { max_bytes: 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 = OreAes128Bit6ChainedChaCha20;
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, Padding::Fixed { max_bytes: 48 })).is_err()
);
assert!(
VarCipherText::from_slice(&retag(&genuine, Padding::Fixed { max_bytes: 16 })).is_ok()
);
}
#[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!(
OreAes128Bit6ChainedChaCha20::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_length_outputs_pin_the_block_count() {
let c = ore();
let n = 7u128.encrypt(&c).unwrap();
let n_left = 7u128.encrypt_left(&c).unwrap();
let unpadded = ore_with(Padding::None);
let s = unpadded.encrypt_str("alice").unwrap();
let s16 = unpadded.encrypt_str("0123456789abcdef").unwrap();
let s16_padded = c.encrypt_str("0123456789abcdef").unwrap();
assert_eq!(s16_padded.left.xt.len(), U128_BLOCKS);
assert_eq!(n.as_var().left.xt.len(), U128_BLOCKS);
assert_eq!(U128_BLOCKS, 22);
assert_eq!(I128_BLOCKS, 22);
assert_eq!(
VarCipherText::from_slice(&n.to_bytes()).unwrap().to_bytes(),
n.to_bytes()
);
assert_eq!(
VarLeft::from_slice(&n_left.to_bytes()).unwrap().to_bytes(),
n_left.to_bytes()
);
assert!(
OreAes128Bit6ChainedChaCha20::compare_raw_slices(&n.to_bytes(), &s.to_bytes())
.is_some()
);
let cmp = ChainedCipherText::<U128_BLOCKS>::compare_raw_slices;
assert_eq!(cmp(&n.to_bytes(), &s.to_bytes()), None);
assert_eq!(cmp(&s.to_bytes(), &n.to_bytes()), None);
assert_eq!(
ChainedCipherText::<U128_BLOCKS>::compare_left_to_full(
&n_left.to_bytes(),
&s.to_bytes()
),
None
);
assert_eq!(
ChainedCipherText::<U128_BLOCKS>::compare_left_to_full(
&unpadded.encrypt_left_str("alice").unwrap().to_bytes(),
&n.to_bytes()
),
None
);
assert!(cmp(&n.to_bytes(), &s16.to_bytes()).is_some());
assert_eq!(cmp(&n.to_bytes(), &s16_padded.to_bytes()), None);
assert!(ChainedCipherText::<U128_BLOCKS>::from_slice(&s16_padded.to_bytes()).is_err());
assert!(ChainedCipherText::<U128_BLOCKS>::try_from(s16_padded.clone()).is_err());
assert!(ChainedCipherText::<U128_BLOCKS>::from_slice(&s16.to_bytes()).is_ok());
assert!(ChainedCipherText::<U128_BLOCKS>::from_slice(&s.to_bytes()).is_err());
assert!(ChainedLeft::<U128_BLOCKS>::from_slice(
&unpadded.encrypt_left_str("alice").unwrap().to_bytes()
)
.is_err());
assert!(ChainedCipherText::<U128_BLOCKS>::try_from(s.clone()).is_err());
assert!(ChainedCipherText::<U128_BLOCKS>::try_from(n.clone().into_var()).is_ok());
assert!(ChainedCipherText::<23>::from_slice(&n.to_bytes()).is_err());
assert!(ChainedLeft::<23>::from_slice(&n_left.to_bytes()).is_err());
}
#[test]
fn encrypt_fixed_matches_the_typed_path() {
let c = ore();
let x = 0x0123_4567_89ab_cdef_u128 << 64 | 0xfedc_ba98_7654_3210;
assert_eq!(
c.encrypt_left_fixed(&x).unwrap().to_bytes(),
x.encrypt_left(&c).unwrap().to_bytes()
);
let blocks = bytes_to_blocks(&x.to_be_bytes()).unwrap();
assert_eq!(
c.encrypt_left_var(blocks.as_bytes()).unwrap().to_bytes(),
x.encrypt_left(&c).unwrap().to_bytes()
);
let ct = c.encrypt_fixed(&x).unwrap();
assert!(ChainedCipherText::<U128_BLOCKS>::from_slice(&ct.to_bytes()).is_ok());
}
#[test]
fn fixed_types_past_the_wire_limit_are_refused_by_length() {
let c = ore();
let too_wide = Box::new([0u8; MAX_STR_BYTES + 1]);
assert!(matches!(
c.encrypt_fixed(&*too_wide),
Err(OreError::TooManyBlocks)
));
assert!(matches!(
c.encrypt_left_fixed(&*too_wide),
Err(OreError::TooManyBlocks)
));
assert!(matches!(check_fixed_len::<[u8; MAX_STR_BYTES]>(), Ok(())));
assert!(matches!(
check_fixed_len::<[u8; MAX_STR_BYTES + 1]>(),
Err(OreError::TooManyBlocks)
));
}
#[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| v.encrypt(&c).unwrap().to_bytes())
.collect();
for (i, a) in cts.iter().enumerate() {
for (j, b) in cts.iter().enumerate() {
assert_eq!(
ChainedCipherText::<I128_BLOCKS>::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!(
OreAes128Bit6ChainedChaCha20::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!(
OreAes128Bit6ChainedChaCha20::compare_left_to_full(&left, &full),
Some(Ordering::Equal)
);
assert_eq!(
OreAes128Bit6ChainedChaCha20::compare_raw_slices(&left, &full),
None
);
assert_eq!(
OreAes128Bit6ChainedChaCha20::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: &OreAes128Bit6ChainedChaCha20, 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));
OreAes128Bit6ChainedChaCha20::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);
OreAes128Bit6ChainedChaCha20::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));
OreAes128Bit6ChainedChaCha20::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();
OreAes128Bit6ChainedChaCha20::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();
OreAes128Bit6ChainedChaCha20::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 = OreAes128Bit6ChainedChaCha20;
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 = OreAes128Bit6ChainedChaCha20;
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, cb) = (a.encrypt(&c).unwrap().to_bytes(), b.encrypt(&c).unwrap().to_bytes());
let la = a.encrypt_left(&c).unwrap().to_bytes();
ChainedCipherText::<U128_BLOCKS>::compare_raw_slices(&ca, &cb) == Some(a.cmp(&b))
&& ChainedCipherText::<U128_BLOCKS>::compare_left_to_full(&la, &cb) == Some(a.cmp(&b))
}
fn prop_i128_order(a: i128, b: i128) -> bool {
let c = ore();
let (ca, cb) = (a.encrypt(&c).unwrap().to_bytes(), b.encrypt(&c).unwrap().to_bytes());
let la = a.encrypt_left(&c).unwrap().to_bytes();
ChainedCipherText::<I128_BLOCKS>::compare_raw_slices(&ca, &cb) == Some(a.cmp(&b))
&& ChainedCipherText::<I128_BLOCKS>::compare_left_to_full(&la, &cb) == 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 = OreAes128Bit6ChainedChaCha20::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: &OreAes128Bit6ChainedChaCha20, 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(&OreAes128Bit6ChainedChaCha20, &str),
unscrubbed: fn(&OreAes128Bit6ChainedChaCha20, &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_fixed_plaintext(encrypt: fn(&OreAes128Bit6ChainedChaCha20, &[u8; MAX_STR_BYTES])) {
use crate::primitives::stack::{residue, SCRUB_BYTES};
fn plaintext() -> Box<[u8; MAX_STR_BYTES]> {
let v: Vec<u8> = (0..MAX_STR_BYTES).map(|i| (i * 37 + 11) as u8).collect();
v.into_boxed_slice().try_into().unwrap()
}
let p = plaintext();
let needles: Vec<Vec<u8>> = [0, MAX_STR_BYTES / 2, MAX_STR_BYTES - 64]
.iter()
.map(|&at| p[at..at + 64].to_vec())
.collect();
if MAX_STR_BYTES > SCRUB_BYTES {
let dead = residue::after(|| {
let p = plaintext();
stack::scrubbed(|| {
core::hint::black_box(p.to_fixed_orderable_bytes());
});
});
assert!(needles.iter().any(|n| residue::contains(&dead, n)));
}
let dead = residue::after(move || encrypt(&ore(), &plaintext()));
for needle in &needles {
assert!(
!residue::contains(&dead, needle),
"plaintext left in dead stack"
);
}
}
#[test]
fn encrypt_fixed_leaves_no_large_array_on_the_stack() {
assert_no_fixed_plaintext(|ore, x| {
core::hint::black_box(ore.encrypt_fixed(x).unwrap());
});
}
#[test]
fn encrypt_left_fixed_leaves_no_large_array_on_the_stack() {
assert_no_fixed_plaintext(|ore, x| {
core::hint::black_box(ore.encrypt_left_fixed(x).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());
},
);
}
}