#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::fmt;
use sha2::{Digest, Sha256};
pub mod alphabets;
mod cycle;
mod ff1;
pub use cycle::{CyclingBuilder, CyclingDealcode};
use alphabets::ResolvedAlphabet;
use ff1::AesCipher;
const COUNTER_BOUND: u128 = 1 << 63;
const TWEAK_PREFIX: &str = "dealcode/v1/";
const KDF_PREFIX: &[u8] = b"dealcode/v1/kdf";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Config(String),
Range {
n: u64,
capacity: u64,
},
InvalidCode(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Config(msg) => write!(f, "invalid configuration: {msg}"),
Error::Range { n, capacity } => {
write!(f, "counter {n} out of range [0, {capacity})")
}
Error::InvalidCode(msg) => write!(f, "invalid code: {msg}"),
}
}
}
impl std::error::Error for Error {}
#[derive(Clone)]
pub struct Key(KeyRepr);
#[derive(Clone)]
enum KeyRepr {
Bytes(Vec<u8>),
Text(String),
}
impl Key {
fn resolve(&self) -> Result<Vec<u8>, Error> {
let (material, is_bytes) = match &self.0 {
KeyRepr::Bytes(b) => (b.as_slice(), true),
KeyRepr::Text(s) => (s.as_bytes(), false),
};
if material.is_empty() {
return Err(Error::Config("key must not be empty".to_owned()));
}
if !is_bytes && material.contains(&0) {
return Err(Error::Config(
"string key material must not contain U+0000".to_owned(),
));
}
if let KeyRepr::Text(s) = &self.0 {
if alphabets::PRESET_NAMES.contains(&s.to_ascii_lowercase().as_str()) {
return Err(Error::Config(format!(
"string key {s:?} is a preset alphabet name — \
did you swap the key and alphabet arguments?"
)));
}
}
if is_bytes && matches!(material.len(), 16 | 24 | 32) {
return Ok(material.to_vec());
}
let mut hasher = Sha256::new();
hasher.update(KDF_PREFIX);
hasher.update(material);
Ok(hasher.finalize().to_vec())
}
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Key(..)")
}
}
impl From<&str> for Key {
fn from(s: &str) -> Self {
Key(KeyRepr::Text(s.to_owned()))
}
}
impl From<String> for Key {
fn from(s: String) -> Self {
Key(KeyRepr::Text(s))
}
}
impl From<&[u8]> for Key {
fn from(b: &[u8]) -> Self {
Key(KeyRepr::Bytes(b.to_vec()))
}
}
impl From<Vec<u8>> for Key {
fn from(b: Vec<u8>) -> Self {
Key(KeyRepr::Bytes(b))
}
}
impl<const N: usize> From<[u8; N]> for Key {
fn from(b: [u8; N]) -> Self {
Key(KeyRepr::Bytes(b.to_vec()))
}
}
impl<const N: usize> From<&[u8; N]> for Key {
fn from(b: &[u8; N]) -> Self {
Key(KeyRepr::Bytes(b.to_vec()))
}
}
#[derive(Clone, Debug)]
#[must_use = "call .build() to construct the codec"]
pub struct Builder {
key: Key,
alphabet: String,
min_length: usize,
max_length: Option<usize>,
domain: String,
}
impl Builder {
pub fn alphabet(mut self, alphabet: impl Into<String>) -> Self {
self.alphabet = alphabet.into();
self
}
pub fn min_length(mut self, min_length: usize) -> Self {
self.min_length = min_length;
self
}
pub fn max_length(mut self, max_length: usize) -> Self {
self.max_length = Some(max_length);
self
}
pub fn domain(mut self, domain: impl Into<String>) -> Self {
self.domain = domain.into();
self
}
pub fn build(self) -> Result<Dealcode, Error> {
Dealcode::from_builder(self)
}
}
#[derive(Clone)]
pub struct Dealcode {
alphabet: ResolvedAlphabet,
char_index: [u8; 128],
radix: u32,
min_length: usize,
max_length: usize,
domain: String,
capacity: u64,
cipher: AesCipher,
powers: Vec<u128>,
params: Vec<ff1::Params>,
}
const NO_NUMERAL: u8 = 0xFF;
impl Dealcode {
pub fn new(key: impl Into<Key>) -> Result<Self, Error> {
Self::builder(key).build()
}
pub fn builder(key: impl Into<Key>) -> Builder {
Builder {
key: key.into(),
alphabet: "hex".to_owned(),
min_length: 6,
max_length: None,
domain: String::new(),
}
}
fn from_builder(builder: Builder) -> Result<Self, Error> {
let aes_key = builder.key.resolve()?;
let alphabet = alphabets::resolve(&builder.alphabet).map_err(Error::Config)?;
let radix = alphabet.chars.chars().count() as u32;
let r = u128::from(radix);
let min_length = builder.min_length;
if !(2..=128).contains(&min_length) {
return Err(Error::Config(
"min_length must be in [2, 128]".to_owned(),
));
}
let min_ok = u32::try_from(min_length)
.ok()
.map_or(true, |e| r.checked_pow(e).map_or(true, |p| p >= 100));
if !min_ok {
return Err(Error::Config(
"radix^min_length must be at least 100 (FF1 minimum domain)".to_owned(),
));
}
let max_length = builder
.max_length
.unwrap_or_else(|| default_max_length(r, min_length));
if max_length < min_length {
return Err(Error::Config(
"max_length must be at least min_length".to_owned(),
));
}
let floor_2_128_div_r = (u128::MAX - (r - 1)) / r + 1;
let max_ok = max_length <= 128
&& r
.checked_pow((max_length - 1) as u32)
.map_or(false, |p| p <= floor_2_128_div_r);
if !max_ok {
return Err(Error::Config(
"radix^max_length must not exceed 2^128".to_owned(),
));
}
if builder.domain.as_bytes().contains(&0) {
return Err(Error::Config(
"domain must not contain U+0000".to_owned(),
));
}
if builder.domain.len() > 255 {
return Err(Error::Config(
"domain must be at most 255 UTF-8 bytes".to_owned(),
));
}
let mut char_index = [NO_NUMERAL; 128];
for (i, c) in alphabet.chars.chars().enumerate() {
char_index[c as usize] = i as u8; }
let tweak = [TWEAK_PREFIX.as_bytes(), builder.domain.as_bytes()].concat();
let powers: Vec<u128> = (0..max_length as u32).map(|d| r.pow(d)).collect();
let capacity = match r.checked_pow(max_length as u32) {
Some(p) if p < COUNTER_BOUND => p as u64,
_ => COUNTER_BOUND as u64, };
let cipher = AesCipher::new(&aes_key);
let params = (min_length..=max_length)
.map(|d| ff1::params(radix, &tweak, d))
.collect();
Ok(Dealcode {
alphabet,
char_index,
radix,
min_length,
max_length,
domain: builder.domain,
capacity,
cipher,
powers,
params,
})
}
pub fn alphabet(&self) -> &str {
&self.alphabet.chars
}
pub fn radix(&self) -> u32 {
self.radix
}
pub fn min_length(&self) -> usize {
self.min_length
}
pub fn max_length(&self) -> usize {
self.max_length
}
pub fn domain(&self) -> &str {
&self.domain
}
pub fn capacity(&self) -> u64 {
self.capacity
}
pub fn encode(&self, n: u64) -> Result<String, Error> {
if n >= self.capacity {
return Err(Error::Range { n, capacity: self.capacity });
}
let n = u128::from(n);
let mut d = self.min_length;
while d < self.max_length && n >= self.powers[d] {
d += 1;
}
let base = if d == self.min_length { 0 } else { self.powers[d - 1] };
let mut v = n - base;
let r = u128::from(self.radix);
let mut numerals = vec![0u8; d];
for slot in numerals.iter_mut().rev() {
*slot = (v % r) as u8;
v /= r;
}
let cipher_text = ff1::encrypt(
&self.cipher,
&self.params[d - self.min_length],
self.radix,
&numerals,
);
let alphabet = self.alphabet.chars.as_bytes();
let bytes: Vec<u8> = cipher_text.iter().map(|&x| alphabet[x as usize]).collect();
Ok(String::from_utf8(bytes).expect("alphabet is ASCII"))
}
pub fn decode(&self, code: &str) -> Result<u64, Error> {
let d = code.chars().count();
if d < self.min_length || d > self.max_length {
return Err(Error::InvalidCode(format!(
"code length {d} outside [{}, {}]",
self.min_length, self.max_length
)));
}
let mut numerals = Vec::with_capacity(d);
for c in code.chars() {
let c = self.alphabet.normalization.apply(c);
let numeral = if c.is_ascii() { self.char_index[c as usize] } else { NO_NUMERAL };
if numeral == NO_NUMERAL {
return Err(Error::InvalidCode(format!("character {c:?} not in alphabet")));
}
numerals.push(numeral);
}
let plain = ff1::decrypt(
&self.cipher,
&self.params[d - self.min_length],
self.radix,
&numerals,
);
let v = ff1::num(u128::from(self.radix), &plain);
let base = if d == self.min_length { 0 } else { self.powers[d - 1] };
if d > self.min_length {
let stage_capacity = base * (u128::from(self.radix) - 1);
if v >= stage_capacity {
return Err(Error::InvalidCode("code was not issued by this codec".to_owned()));
}
}
let n = base + v;
if n >= COUNTER_BOUND {
return Err(Error::InvalidCode("code was not issued by this codec".to_owned()));
}
Ok(n as u64)
}
}
impl fmt::Debug for Dealcode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self.alphabet.name {
Some(name) => name.to_owned(),
None => format!("custom({})", self.radix),
};
f.debug_struct("Dealcode")
.field("alphabet", &name)
.field("min_length", &self.min_length)
.field("max_length", &self.max_length)
.field("domain", &self.domain)
.finish_non_exhaustive()
}
}
fn default_max_length(radix: u128, min_length: usize) -> usize {
let exp = match u32::try_from(min_length) {
Ok(e) => e,
Err(_) => return min_length, };
let mut length = min_length;
let mut cap = match radix.checked_pow(exp) {
Some(c) => c,
None => return min_length, };
while cap.checked_mul(radix).map_or(false, |next| next < COUNTER_BOUND) {
cap *= radix;
length += 1;
}
length
}
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Dealcode>();
assert_send_sync::<CyclingDealcode>();
assert_send_sync::<CyclingBuilder>();
assert_send_sync::<Key>();
assert_send_sync::<Builder>();
assert_send_sync::<Error>();
};