use wordlists::PGPFONE;
pub(crate) fn max_word_len() -> usize {
(0..256_usize)
.flat_map(|i| [PGPFONE.word(&i, 0).unwrap(), PGPFONE.word(&i, 1).unwrap()])
.map(|w| w.len())
.max()
.unwrap_or(0)
}
pub(crate) fn bytes_to_wordlist(bytes: &Vec<u8>) -> Vec<&'static str> {
let mut wordlist = Vec::new();
for (i, b) in bytes.iter().enumerate() {
let word = PGPFONE
.word(&(*b as usize), i)
.expect("Invalid byte value.");
wordlist.push(word);
}
wordlist
}
pub(crate) fn wordlist_to_bytes(wordlist: &Vec<&str>) -> Vec<u8> {
let mut bytes = Vec::new();
for (i, word) in wordlist.iter().enumerate() {
let byte = (0..256_usize)
.find(|&idx| {
PGPFONE
.word(&idx, i)
.map(|w| w.eq_ignore_ascii_case(word))
.unwrap_or(false)
})
.expect("Unknown PGPfone word") as u8;
bytes.push(byte);
}
bytes
}
#[cfg(test)]
mod test {
use super::{bytes_to_wordlist, wordlist_to_bytes};
#[test]
fn validate_lists_complete() {
use wordlists::PGPFONE;
for i in 0..256_usize {
assert!(!PGPFONE.word(&i, 0).unwrap().is_empty());
assert!(!PGPFONE.word(&i, 1).unwrap().is_empty());
}
}
#[test]
fn validate_convert() {
let patrick: Vec<u8> = vec![
0x5C, 0x39, 0x76, 0xD5, 0xDD, 0xE2, 0x9E, 0xC2, 0x56, 0x2C, 0xA2, 0x91, 0xC7, 0x91,
0x65, 0xF9,
];
let wordlist = bytes_to_wordlist(&patrick);
assert_eq!(
wordlist,
vec![
"escape",
"corporate",
"inverse",
"specialist",
"swelter",
"tomorrow",
"quiver",
"repellent",
"egghead",
"Chicago",
"rebirth",
"miracle",
"soybean",
"miracle",
"fracture",
"Waterloo"
],
"Verify we can create the expected wordlist from a list of bytes."
);
assert_eq!(
patrick,
wordlist_to_bytes(&wordlist),
"Verify we can convert back to bytes from a known wordlist."
);
}
}