The Algorithms logo
The Algorithms
À proposFaire un don

Blake 2b

// For specification go to https://www.rfc-editor.org/rfc/rfc7693

use std::cmp::{max, min};
use std::convert::{TryFrom, TryInto};

type Word = u64;

const BB: usize = 128;

const U64BYTES: usize = (u64::BITS as usize) / 8;

type Block = [Word; BB / U64BYTES];

const KK_MAX: usize = 64;
const NN_MAX: u8 = 64;

// Array of round constants used in mixing function G
const RC: [u32; 4] = [32, 24, 16, 63];

// IV[i] = floor(2**64 * frac(sqrt(prime(i+1)))) where prime(i) is the ith prime number
const IV: [Word; 8] = [
    0x6A09E667F3BCC908,
    0xBB67AE8584CAA73B,
    0x3C6EF372FE94F82B,
    0xA54FF53A5F1D36F1,
    0x510E527FADE682D1,
    0x9B05688C2B3E6C1F,
    0x1F83D9ABFB41BD6B,
    0x5BE0CD19137E2179,
];

const SIGMA: [[usize; 16]; 10] = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
    [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
    [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
    [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
    [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
    [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
    [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
    [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
    [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
    [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
];

#[inline]
const fn blank_block() -> Block {
    [0u64; BB / U64BYTES]
}

// Overflowing addition
#[inline]
fn add(a: &mut Word, b: Word) {
    *a = a.overflowing_add(b).0;
}

#[inline]
const fn ceil(dividend: usize, divisor: usize) -> usize {
    (dividend / divisor) + ((dividend % divisor != 0) as usize)
}

fn g(v: &mut [Word; 16], a: usize, b: usize, c: usize, d: usize, x: Word, y: Word) {
    for (m, r) in [x, y].into_iter().zip(RC.chunks(2)) {
        let v_b = v[b];
        add(&mut v[a], v_b);
        add(&mut v[a], m);

        v[d] = (v[d] ^ v[a]).rotate_right(r[0]);

        let v_d = v[d];
        add(&mut v[c], v_d);

        v[b] = (v[b] ^ v[c]).rotate_right(r[1]);
    }
}

fn f(h: &mut [Word; 8], m: Block, t: u128, flag: bool) {
    let mut v: [Word; 16] = [0; 16];

    for (i, (h_i, iv_i)) in h.iter().zip(IV.iter()).enumerate() {
        v[i] = *h_i;
        v[i + 8] = *iv_i;
    }

    v[12] ^= (t % (u64::MAX as u128)) as u64;
    v[13] ^= (t >> 64) as u64;

    if flag {
        v[14] = !v[14];
    }

    for i in 0..12 {
        let s = SIGMA[i % 10];

        let mut s_index = 0;
        for j in 0..4 {
            g(
                &mut v,
                j,
                j + 4,
                j + 8,
                j + 12,
                m[s[s_index]],
                m[s[s_index + 1]],
            );

            s_index += 2;
        }

        let i1d = |col, row| {
            let col = col % 4;
            let row = row % 4;

            (row * 4) + col
        };

        for j in 0..4 {
            // Produces indeces for diagonals of a 4x4 matrix starting at 0,j
            let idx: Vec<usize> = (0..4).map(|n| i1d(j + n, n) as usize).collect();

            g(
                &mut v,
                idx[0],
                idx[1],
                idx[2],
                idx[3],
                m[s[s_index]],
                m[s[s_index + 1]],
            );

            s_index += 2;
        }
    }

    for (i, n) in h.iter_mut().enumerate() {
        *n ^= v[i] ^ v[i + 8];
    }
}

fn blake2(d: Vec<Block>, ll: u128, kk: Word, nn: Word) -> Vec<u8> {
    let mut h: [Word; 8] = IV
        .iter()
        .take(8)
        .copied()
        .collect::<Vec<Word>>()
        .try_into()
        .unwrap();

    h[0] ^= 0x01010000u64 ^ (kk << 8) ^ nn;

    if d.len() > 1 {
        for (i, w) in d.iter().enumerate().take(d.len() - 1) {
            f(&mut h, *w, (i as u128 + 1) * BB as u128, false);
        }
    }

    let ll = if kk > 0 { ll + BB as u128 } else { ll };
    f(&mut h, d[d.len() - 1], ll, true);

    h.iter()
        .flat_map(|n| n.to_le_bytes())
        .take(nn as usize)
        .collect()
}

// Take arbitrarily long slice of u8's and turn up to 8 bytes into u64
fn bytes_to_word(bytes: &[u8]) -> Word {
    if let Ok(arr) = <[u8; U64BYTES]>::try_from(bytes) {
        Word::from_le_bytes(arr)
    } else {
        let mut arr = [0u8; 8];
        for (a_i, b_i) in arr.iter_mut().zip(bytes) {
            *a_i = *b_i;
        }

        Word::from_le_bytes(arr)
    }
}

pub fn blake2b(m: &[u8], k: &[u8], nn: u8) -> Vec<u8> {
    let kk = min(k.len(), KK_MAX);
    let nn = min(nn, NN_MAX);

    // Prevent user from giving a key that is too long
    let k = &k[..kk];

    let dd = max(ceil(kk, BB) + ceil(m.len(), BB), 1);

    let mut blocks: Vec<Block> = vec![blank_block(); dd];

    // Copy key into blocks
    for (w, c) in blocks[0].iter_mut().zip(k.chunks(U64BYTES)) {
        *w = bytes_to_word(c);
    }

    let first_index = (kk > 0) as usize;

    // Copy bytes from message into blocks
    for (i, c) in m.chunks(U64BYTES).enumerate() {
        let block_index = first_index + (i / (BB / U64BYTES));
        let word_in_block = i % (BB / U64BYTES);

        blocks[block_index][word_in_block] = bytes_to_word(c);
    }

    blake2(blocks, m.len() as u128, kk as u64, nn as Word)
}

#[cfg(test)]
mod test {
    use super::*;

    macro_rules! digest_test {
        ($fname:ident, $message:expr, $key:expr, $nn:literal, $expected:expr) => {
            #[test]
            fn $fname() {
                let digest = blake2b($message, $key, $nn);

                let expected = Vec::from($expected);

                assert_eq!(digest, expected);
            }
        };
    }

    digest_test!(
        blake2b_from_rfc,
        &[0x61, 0x62, 0x63],
        &[0; 0],
        64,
        [
            0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D, 0x6A, 0x27, 0x97, 0xB6, 0x9F, 0x12,
            0xF6, 0xE9, 0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A, 0xC4, 0xB7, 0x4B, 0x12, 0xBB, 0x6F,
            0xDB, 0xFF, 0xA2, 0xD1, 0x7D, 0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D, 0xC2, 0x52,
            0xD5, 0xDE, 0x45, 0x33, 0xCC, 0x95, 0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92, 0x5A,
            0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23
        ]
    );

    digest_test!(
        blake2b_empty,
        &[0; 0],
        &[0; 0],
        64,
        [
            0x78, 0x6a, 0x02, 0xf7, 0x42, 0x01, 0x59, 0x03, 0xc6, 0xc6, 0xfd, 0x85, 0x25, 0x52,
            0xd2, 0x72, 0x91, 0x2f, 0x47, 0x40, 0xe1, 0x58, 0x47, 0x61, 0x8a, 0x86, 0xe2, 0x17,
            0xf7, 0x1f, 0x54, 0x19, 0xd2, 0x5e, 0x10, 0x31, 0xaf, 0xee, 0x58, 0x53, 0x13, 0x89,
            0x64, 0x44, 0x93, 0x4e, 0xb0, 0x4b, 0x90, 0x3a, 0x68, 0x5b, 0x14, 0x48, 0xb7, 0x55,
            0xd5, 0x6f, 0x70, 0x1a, 0xfe, 0x9b, 0xe2, 0xce
        ]
    );

    digest_test!(
        blake2b_empty_with_key,
        &[0; 0],
        &[
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
            0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
            0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f
        ],
        64,
        [
            0x10, 0xeb, 0xb6, 0x77, 0x00, 0xb1, 0x86, 0x8e, 0xfb, 0x44, 0x17, 0x98, 0x7a, 0xcf,
            0x46, 0x90, 0xae, 0x9d, 0x97, 0x2f, 0xb7, 0xa5, 0x90, 0xc2, 0xf0, 0x28, 0x71, 0x79,
            0x9a, 0xaa, 0x47, 0x86, 0xb5, 0xe9, 0x96, 0xe8, 0xf0, 0xf4, 0xeb, 0x98, 0x1f, 0xc2,
            0x14, 0xb0, 0x05, 0xf4, 0x2d, 0x2f, 0xf4, 0x23, 0x34, 0x99, 0x39, 0x16, 0x53, 0xdf,
            0x7a, 0xef, 0xcb, 0xc1, 0x3f, 0xc5, 0x15, 0x68
        ]
    );

    digest_test!(
        blake2b_key_shortin,
        &[0],
        &[
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
            0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
            0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f
        ],
        64,
        [
            0x96, 0x1f, 0x6d, 0xd1, 0xe4, 0xdd, 0x30, 0xf6, 0x39, 0x01, 0x69, 0x0c, 0x51, 0x2e,
            0x78, 0xe4, 0xb4, 0x5e, 0x47, 0x42, 0xed, 0x19, 0x7c, 0x3c, 0x5e, 0x45, 0xc5, 0x49,
            0xfd, 0x25, 0xf2, 0xe4, 0x18, 0x7b, 0x0b, 0xc9, 0xfe, 0x30, 0x49, 0x2b, 0x16, 0xb0,
            0xd0, 0xbc, 0x4e, 0xf9, 0xb0, 0xf3, 0x4c, 0x70, 0x03, 0xfa, 0xc0, 0x9a, 0x5e, 0xf1,
            0x53, 0x2e, 0x69, 0x43, 0x02, 0x34, 0xce, 0xbd
        ]
    );

    digest_test!(
        blake2b_keyed_filled,
        &[
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
            0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
            0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f
        ],
        &[
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
            0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
            0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f
        ],
        64,
        [
            0x65, 0x67, 0x6d, 0x80, 0x06, 0x17, 0x97, 0x2f, 0xbd, 0x87, 0xe4, 0xb9, 0x51, 0x4e,
            0x1c, 0x67, 0x40, 0x2b, 0x7a, 0x33, 0x10, 0x96, 0xd3, 0xbf, 0xac, 0x22, 0xf1, 0xab,
            0xb9, 0x53, 0x74, 0xab, 0xc9, 0x42, 0xf1, 0x6e, 0x9a, 0xb0, 0xea, 0xd3, 0x3b, 0x87,
            0xc9, 0x19, 0x68, 0xa6, 0xe5, 0x09, 0xe1, 0x19, 0xff, 0x07, 0x78, 0x7b, 0x3e, 0xf4,
            0x83, 0xe1, 0xdc, 0xdc, 0xcf, 0x6e, 0x30, 0x22
        ]
    );
}