libhardcopy 1.0.0

Generalized library for hardcopy/softcopy command line utilities.
Documentation
use std::convert::TryInto;

use wordlists::SKEYOTP_WORDLIST;

pub const SKEY_OTP_INSTRUCTIONS: &str =
    include_str!("../../../static/wordlists/skeyotp/instructions.txt");

/// Returns the length of the longest word in the S/KEY OTP list.
pub(crate) fn max_word_len() -> usize {
    SKEYOTP_WORDLIST.iter().map(|w| w.len()).max().unwrap_or(0)
}

/// Compute the S/KEY 2-bit checksum: sum of all 32 two-bit pairs of a
/// 64-bit data block, taken mod 4.
fn sum_of_pairs(block: u64) -> u8 {
    let mut sum: u32 = 0;
    let mut v = block;
    for _ in 0..32 {
        sum += (v & 0x03) as u32;
        v >>= 2;
    }
    (sum & 0x03) as u8
}

/// Encode one 8-byte (64-bit) block into 6 S/KEY OTP words.
///
/// The 64 data bits followed by a 2-bit checksum yield 66 bits total,
/// which are split into 6 x 11-bit indices into the 2048-word list.
fn block_to_words(block: u64) -> [&'static str; 6] {
    let checksum = sum_of_pairs(block) as u128;
    // 66-bit value: bits 65..2 = data, bits 1..0 = checksum
    let value66: u128 = ((block as u128) << 2) | checksum;
    let mut words = [""; 6];
    for i in 0..6usize {
        let shift = (5 - i) * 11;
        let index = ((value66 >> shift) & 0x7FF) as usize;
        words[i] = SKEYOTP_WORDLIST[index];
    }
    words
}

/// Decode 6 S/KEY OTP words back into a 64-bit data block.
fn words_to_block(words: &[&str; 6]) -> u64 {
    let mut value66: u128 = 0;
    for (i, word) in words.iter().enumerate() {
        let index = SKEYOTP_WORDLIST
            .iter()
            .position(|s| s.eq_ignore_ascii_case(word))
            .expect("Unknown S/KEY OTP word") as u128;
        let shift = (5 - i) * 11;
        value66 |= index << shift;
    }
    // Discard the 2 checksum bits at the bottom
    (value66 >> 2) as u64
}

/// Encode `bytes` as S/KEY OTP words.
///
/// A 4-byte little-endian length prefix is prepended, then the data is
/// zero-padded to an 8-byte boundary.  Each 8-byte block is encoded into
/// 6 words (64 data bits + 2-bit checksum = 66 bits per block).
pub(crate) fn bytes_to_wordlist(bytes: &[u8]) -> Vec<&'static str> {
    let len = bytes.len() as u32;
    let mut data = Vec::with_capacity(4 + bytes.len());
    data.extend_from_slice(&len.to_le_bytes());
    data.extend_from_slice(bytes);
    while data.len() % 8 != 0 {
        data.push(0u8);
    }
    let mut words = Vec::with_capacity(data.len() / 8 * 6);
    for chunk in data.chunks_exact(8) {
        let block = u64::from_be_bytes(chunk.try_into().unwrap());
        words.extend_from_slice(&block_to_words(block));
    }
    words
}

/// Decode S/KEY OTP words back to the original bytes, stripping the
/// 4-byte length prefix inserted by `bytes_to_wordlist`.
pub(crate) fn wordlist_to_bytes(words: &[&str]) -> Vec<u8> {
    assert_eq!(words.len() % 6, 0, "word count must be a multiple of 6");
    let mut data = Vec::with_capacity(words.len() / 6 * 8);
    for chunk in words.chunks_exact(6) {
        let block_words: &[&str; 6] = chunk.try_into().unwrap();
        let block = words_to_block(block_words);
        data.extend_from_slice(&block.to_be_bytes());
    }
    if data.len() < 4 {
        return Vec::new();
    }
    let len = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
    data[4..][..len].to_vec()
}

#[cfg(test)]
mod test {
    use super::{
        bytes_to_wordlist, sum_of_pairs, wordlist_to_bytes, SKEYOTP_WORDLIST, SKEY_OTP_INSTRUCTIONS,
    };

    #[test]
    fn validate_list_complete() {
        assert_eq!(2048, SKEYOTP_WORDLIST.len());
        SKEYOTP_WORDLIST.iter().for_each(|v| assert!(!v.is_empty()));
    }

    #[test]
    fn validate_instructions_non_empty() {
        assert!(!SKEY_OTP_INSTRUCTIONS.is_empty());
    }

    #[test]
    fn validate_sum_of_pairs() {
        assert_eq!(0, sum_of_pairs(0u64));
        // All ones: 32 * 3 = 96, 96 mod 4 = 0
        assert_eq!(0, sum_of_pairs(u64::MAX));
        // 0x5555... = repeated 0b01: 32 * 1 = 32, 32 mod 4 = 0
        assert_eq!(0, sum_of_pairs(0x5555555555555555u64));
        // 0xAAAA... = repeated 0b10: 32 * 2 = 64, 64 mod 4 = 0
        assert_eq!(0, sum_of_pairs(0xAAAAAAAAAAAAAAAAu64));
        // Single pair = 0b11 in low 2 bits: sum = 3, mod 4 = 3
        assert_eq!(3, sum_of_pairs(0x03u64));
    }

    #[test]
    fn validate_roundtrip_short() {
        let original: Vec<u8> = vec![0x85, 0xc4, 0x3e, 0xe0, 0x38, 0x57, 0x76, 0x5b];
        let words = bytes_to_wordlist(&original);
        assert_eq!(words.len() % 6, 0);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_unaligned() {
        // 7 bytes — not 8-byte aligned, exercises zero-padding
        let original: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7];
        let words = bytes_to_wordlist(&original);
        assert_eq!(words.len() % 6, 0);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }

    #[test]
    fn validate_roundtrip_empty() {
        let original: Vec<u8> = vec![];
        let words = bytes_to_wordlist(&original);
        let word_refs: Vec<&str> = words.iter().copied().collect();
        assert_eq!(original, wordlist_to_bytes(&word_refs));
    }
}