Functional Weave
Code in Rust

crypto.pbkdf2-sha256@1.0.0

impl/rust.rs

7,251 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

// PBKDF2 calls HMAC-SHA256 once per iteration, so a login at 600,000
// iterations is 1.2 million SHA-256 compressions. The key's inner and outer
// pad blocks are the same every time, so their compressed states are
// computed once and reused, and each iteration hashes a 32-byte value that
// fits one block, so the loop runs on fixed arrays with no allocation. That
// needs SHA-256's compression function itself, which the crypto.sha256
// capability does not expose, so it is written out here.

/// FIPS 180-4 section 4.2.2.
const K: [u32; 64] = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];

const H0: [u32; 8] = [
    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];

fn compress(state: &mut [u32; 8], block: &[u32; 16]) {
    let mut w = [0u32; 64];
    w[..16].copy_from_slice(block);
    for t in 16..64 {
        let s0 = w[t - 15].rotate_right(7) ^ w[t - 15].rotate_right(18) ^ (w[t - 15] >> 3);
        let s1 = w[t - 2].rotate_right(17) ^ w[t - 2].rotate_right(19) ^ (w[t - 2] >> 10);
        w[t] = w[t - 16].wrapping_add(s0).wrapping_add(w[t - 7]).wrapping_add(s1);
    }
    let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state;
    for t in 0..64 {
        let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
        let t1 = h
            .wrapping_add(s1)
            .wrapping_add((e & f) ^ (!e & g))
            .wrapping_add(K[t])
            .wrapping_add(w[t]);
        let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
        let t2 = s0.wrapping_add((a & b) ^ (a & c) ^ (b & c));
        h = g;
        g = f;
        f = e;
        e = d.wrapping_add(t1);
        d = c;
        c = b;
        b = a;
        a = t1.wrapping_add(t2);
    }
    for (slot, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
        *slot = slot.wrapping_add(v);
    }
}

/// SHA-256 of `bytes`, continuing from `state` after `prefix_blocks` blocks
/// already absorbed.
fn hash_from(state: &[u32; 8], prefix_blocks: u64, bytes: &[u8]) -> [u32; 8] {
    let mut s = *state;
    let bit_length = (prefix_blocks * 64 + bytes.len() as u64).wrapping_mul(8);
    let mut padded = bytes.to_vec();
    padded.push(0x80);
    while padded.len() % 64 != 56 {
        padded.push(0);
    }
    padded.extend_from_slice(&bit_length.to_be_bytes());
    let mut block = [0u32; 16];
    for chunk in padded.chunks_exact(64) {
        for t in 0..16 {
            block[t] = u32::from_be_bytes([chunk[t * 4], chunk[t * 4 + 1], chunk[t * 4 + 2], chunk[t * 4 + 3]]);
        }
        compress(&mut s, &block);
    }
    s
}

fn to_bytes(value: &[i64], name: &str) -> Vec<u8> {
    value
        .iter()
        .map(|&b| {
            if !(0..=255).contains(&b) {
                panic!("{} must be a list of integers from 0 to 255", name);
            }
            b as u8
        })
        .collect()
}

/// PBKDF2-HMAC-SHA256 (RFC 8018 section 5.2): for each 32-byte block i of
/// the key, U1 = HMAC(P, S || INT(i)), Uj = HMAC(P, Uj-1), and the block is
/// the XOR of U1..Uc.
///
/// # Panics
/// Panics on a value outside 0-255, fewer than 1 iteration or a key length
/// below 1.
pub fn pbkdf2_sha256(password: &[i64], salt: &[i64], iterations: i64, key_length: i64) -> Vec<i64> {
    let mut key = to_bytes(password, "password");
    let salt = to_bytes(salt, "salt");
    if iterations < 1 {
        panic!("iterations must be a whole number of at least 1");
    }
    if key_length < 1 {
        panic!("keyLength must be a whole number of at least 1");
    }
    if key.len() > 64 {
        key = hash_from(&H0, 0, &key).iter().flat_map(|w| w.to_be_bytes()).collect();
    }
    let mut pad = [0u32; 16];
    for t in 0..16 {
        let mut word = 0u32;
        for k in 0..4 {
            let i = t * 4 + k;
            word = (word << 8) | u32::from(key.get(i).copied().unwrap_or(0) ^ 0x36);
        }
        pad[t] = word;
    }
    let mut inner_state = H0;
    compress(&mut inner_state, &pad);
    for word in pad.iter_mut() {
        *word ^= 0x3636_3636 ^ 0x5c5c_5c5c;
    }
    let mut outer_state = H0;
    compress(&mut outer_state, &pad);

    // A 32-byte message after a 64-byte pad block is one padded block: the
    // digest words, 0x80, zeros and the length, 96 bytes = 768 bits.
    let mut msg = [0u32; 16];
    msg[8] = 0x8000_0000;
    msg[15] = 768;

    let key_length = key_length as usize;
    let mut out: Vec<i64> = Vec::with_capacity(key_length);
    let blocks = (key_length + 31) / 32;
    for block_index in 1..=blocks as u32 {
        let mut first = salt.clone();
        first.extend_from_slice(&block_index.to_be_bytes());
        let inner_digest = hash_from(&inner_state, 1, &first);
        msg[..8].copy_from_slice(&inner_digest);
        let mut state = outer_state;
        compress(&mut state, &msg);
        let mut u = state;
        let mut acc = state;
        for _ in 1..iterations {
            msg[..8].copy_from_slice(&u);
            let mut s = inner_state;
            compress(&mut s, &msg);
            msg[..8].copy_from_slice(&s);
            let mut s2 = outer_state;
            compress(&mut s2, &msg);
            u = s2;
            for t in 0..8 {
                acc[t] ^= s2[t];
            }
        }
        for b in acc.iter().flat_map(|w| w.to_be_bytes()) {
            if out.len() < key_length {
                out.push(b as i64);
            }
        }
    }
    out
}

fn bytes_from_value(value: &Value, name: &str) -> Vec<i64> {
    match value {
        Value::Arr(items) => items
            .iter()
            .map(|item| match item {
                Value::Int(i) => *i,
                _ => panic!("{} must be a list of integers from 0 to 255", name),
            })
            .collect(),
        _ => panic!("{} must be a list of integers from 0 to 255", name),
    }
}

fn whole(value: &Value, message: &str) -> i64 {
    match value {
        Value::Int(i) => *i,
        _ => panic!("{}", message),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    let password = bytes_from_value(&args[0], "password");
    let salt = bytes_from_value(&args[1], "salt");
    let iterations = whole(&args[2], "iterations must be a whole number of at least 1");
    let key_length = whole(&args[3], "keyLength must be a whole number of at least 1");
    Value::Arr(pbkdf2_sha256(&password, &salt, iterations, key_length).into_iter().map(Value::Int).collect())
}