Skip to content

Commit

Permalink
remove more old cruft
Browse files Browse the repository at this point in the history
  • Loading branch information
habnabit committed Jul 5, 2024
1 parent 53fbc8e commit bf7d819
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 54 deletions.
44 changes: 44 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ bytes = { version = "1.6.0", default-features = false }
threefish = { version = "0.5.2", default-features = false }
bytemuck = { version = "1.16.1", default-features = false, features = ["min_const_generics"] }
tiny-keccak-1536 = { version = "2.0.2", path = "tiny-keccak-1536", default-features = false, features = ["shake"] }
factorial = { version = "0.4.0", default-features = false }
primal-sieve = { version = "0.3.7", default-features = false }

[dev-dependencies]
parameterized = "2.0.0"
74 changes: 36 additions & 38 deletions src/multibase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,13 @@ use std::collections::BTreeMap;
use std::io::BufRead;
use std::{fs, io, path, str};

use factorial::Factorial;
use num_bigint::BigUint;
use num_traits::{CheckedSub, Euclid, One, ToPrimitive, Zero};

use crate::error::{PassacreError, PassacreError::*, PassacreResult};
use crate::passacre::PassacreGenerator;

fn borrow_string(s: &String) -> Cow<str> {
Cow::Borrowed(s.as_str())
}

fn int_of_bytes(bytes: &[u8]) -> BigUint {
let mut ret = BigUint::zero();
for b in bytes {
ret = (ret << 8) + (*b as usize);
}
ret
}

fn factorial(n: usize) -> BigUint {
if n < 2 {
return BigUint::one();
}
(2..n).fold(BigUint::from(n), |acc, i| acc * BigUint::from(i))
}

fn length_one_string(c: char) -> String {
let mut ret = String::with_capacity(c.len_utf8());
ret.push(c);
ret
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Base {
Separator(String),
Expand All @@ -55,7 +31,7 @@ impl Base {
_ => fail!(UserError),
},
1 if !string.is_empty() => match str::from_utf8(string) {
Ok(s) => Base::Characters(s.chars().map(length_one_string).collect()),
Ok(s) => Base::Characters(s.chars().map(|c| c.into()).collect()),
_ => fail!(UserError),
},
2 if string.is_empty() => Base::Words,
Expand All @@ -74,10 +50,7 @@ struct Words {
impl Words {
fn new(words: Vec<String>) -> Words {
let length = BigUint::from(words.len());
Words {
words: words,
length: length,
}
Words { words, length }
}
}

Expand All @@ -90,7 +63,7 @@ struct BaseInfo {
impl BaseInfo {
fn new(length: BigUint) -> BaseInfo {
BaseInfo {
length: length,
length,
positions: Vec::new(),
}
}
Expand All @@ -106,6 +79,8 @@ pub struct MultiBase {
}

impl MultiBase {
const GENERATOR_ATTEMPTS: usize = 1000;

pub fn new() -> MultiBase {
MultiBase {
bases: BTreeMap::new(),
Expand Down Expand Up @@ -133,9 +108,26 @@ impl MultiBase {
if self.shuffle {
return;
}
// safety: there will be at least one item in the iterator
let highest_int = self
.bases
.values()
.map(|i| i.positions.len())
.chain(Some(self.n_bases))
.max()
.unwrap();
let sieve = primal_sieve::Sieve::new(highest_int);
self.length_product = self.bases.values().fold(
&self.length_product * factorial(self.n_bases),
|acc, info| acc / factorial(info.positions.len()),
// safety: psw_factorial returns None only on overflow
&self.length_product
* <BigUint as From<usize>>::from(self.n_bases)
.psw_factorial(&sieve)
.unwrap(),
|acc, info| {
acc / <BigUint as From<usize>>::from(info.positions.len())
.psw_factorial(&sieve)
.unwrap()
},
);
self.shuffle = true;
}
Expand Down Expand Up @@ -230,6 +222,10 @@ impl MultiBase {
}

fn encode(&self, mut n: BigUint) -> PassacreResult<String> {
fn borrow_string(s: &String) -> Cow<str> {
Cow::Borrowed(s.as_str())
}

if n < BigUint::zero() || n >= self.length_product {
fail!(DomainError);
}
Expand Down Expand Up @@ -259,26 +255,28 @@ impl MultiBase {
}

pub fn encode_from_bytes(&self, bytes: &[u8]) -> PassacreResult<String> {
self.encode(int_of_bytes(bytes))
self.encode(BigUint::from_bytes_be(bytes))
}

pub fn encode_from_generator(&self, gen: &mut PassacreGenerator) -> PassacreResult<String> {
let mut buf = vec![0u8; self.required_bytes()];
loop {
// test this new loop more exhaustively against bad inputs
for _ in 0..Self::GENERATOR_ATTEMPTS {
gen.squeeze(&mut buf)?;
match self.encode(int_of_bytes(&buf)) {
match self.encode(BigUint::from_bytes_be(&buf)) {
Err(PassacreError::DomainError) => continue,
x => return x,
}
}
Err(DomainError)
}
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;

use super::{length_one_string, Base, MultiBase};
use super::{Base, MultiBase};
use crate::error::PassacreError::*;
use parameterized::parameterized;

Expand Down Expand Up @@ -364,7 +362,7 @@ mod tests {
const HEXDIGITS: &'static str = "0123456789abcdef";

fn characters(cs: &'static str) -> Base {
Base::Characters(cs.chars().map(length_one_string).collect())
Base::Characters(cs.chars().map(|c| c.into()).collect())
}

multibase_tests!(
Expand Down
26 changes: 11 additions & 15 deletions src/passacre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use bytes::{BufMut, BytesMut};
use rand::RngCore;
use skein::{Skein512, Digest};
use skein::{Digest, Skein512};
use threefish::Threefish512;
use tiny_keccak_1536::{Hasher, NonstandardShake1536, Xof};

Expand Down Expand Up @@ -57,7 +57,10 @@ impl Kdf {
pub fn derive(&self, username: &[u8], password: &[u8]) -> PassacreResult<Vec<u8>> {
match self {
Kdf::Scrypt(params) => {
testing_fail!(params.log_n() == 99 && params.r() == 99 && params.p() == 99, ScryptError);
testing_fail!(
params.log_n() == 99 && params.r() == 99 && params.p() == 99,
ScryptError
);
let mut ret = vec![0u8; SCRYPT_BUFFER_SIZE];
scrypt::scrypt(password, username, params, &mut ret).map_err(|_| InternalError)?;
Ok(ret)
Expand Down Expand Up @@ -88,7 +91,7 @@ impl HashState {
let nulls = [0u8; SKEIN_512_BLOCK_BYTES];
hash.update(&nulls);
HashState::Skein(hash)
},
}
};
Ok(hash_state)
}
Expand All @@ -103,14 +106,10 @@ pub struct PassacreGenerator {
pub const SCRYPT_BUFFER_SIZE: usize = 64;

const DELIMITER: &'static [u8] = b":";
const TWEAK: [u8; 16] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x3f,
];
const TWEAK: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x3f];
const ONE_IN_64: [u8; 64] = [
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

impl PassacreGenerator {
Expand Down Expand Up @@ -216,7 +215,7 @@ impl PassacreGenerator {
match &mut self.hash_state {
HashState::Keccak(sponge) => {
sponge.squeeze(output);
},
}
HashState::SkeinPrng(skein) => {
let mut n_bytes = output.len();
let mut output_pos = 0usize;
Expand All @@ -231,10 +230,7 @@ impl PassacreGenerator {
skein.threefish = Threefish512::new_with_tweak(&next_state_bytes, &TWEAK);
}
let splut = skein.buffer.split_to(n_bytes.min(skein.buffer.len()));
let copied = copy_from_shorter_slice(
&mut output[output_pos..],
&splut,
);
let copied = copy_from_shorter_slice(&mut output[output_pos..], &splut);
n_bytes -= copied;
output_pos += copied;
}
Expand Down
4 changes: 3 additions & 1 deletion tiny-keccak-1536/src/shake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,14 @@ pub struct NonstandardShake1536 {
}

impl NonstandardShake1536 {
// setting rate = 64 in the old library was only consuming 8 bytes at a time
const RATE: usize = 8;
const DELIM: u8 = 0x01;

/// create this nonstandard thing
pub fn new() -> Self {
Self {
state: KeccakState::new(8, Self::DELIM),
state: KeccakState::new(Self::RATE, Self::DELIM),
}
}
}
Expand Down

0 comments on commit bf7d819

Please sign in to comment.