【密码学】一文读懂Grøstl

admin 2022年8月27日23:46:19评论36 views字数 9756阅读32分31秒阅读模式
【密码学】一文读懂Grøstl

无意中看到一个名字比较有意思的哈希函数,这个哈希函数也是SHA3的候选算法之一,虽然最后没有选他,不过他这个名字起的着实是蛮有意思的,所以呢本文来看一下它的具体的结构。

背景知识

根据参考资料,这个名字来自于德语,原来指的是一道奥地利菜,该菜式的英文名称为哈希,为啥第一眼相中了这个算法呢,因为这个算法俺不会读,然后就去翻了一下他应该是怎么发音的,结果就是 「一入算法深似海,从此天涯是路人」,这里直接截图一段原始论文的原文吧,我也懒得从pdf当中复制出来了。

【密码学】一文读懂Grøstl

本以为这里会给个音标啥的,结果一句话给我整破防了,如果想要了解更多的发音的例子,我还需要看一下另一篇paper,这不就是套娃吗,然后我满怀期待的看了一下所提到的地址,发现这根本不是我这种学渣能够理解的了的,所以干脆我就不纠结他的发音了,咱惹不起还躲不起吗,溜了溜了。

算法过程

虽然说,咱不知道这个算法的名字应该怎么读,但是吧,写文章又不要求我会读,如果有会读的读者,欢迎来告诉我,下面还是来具体的看一下这个算法是怎么玩的吧。

算法构造

这个算法也是按照分块来处理消息的,根据最终所得到的消息摘要的长度,分割长度可以为 512或者为 1024

【密码学】一文读懂Grøstl

上图是我从原始的论文里面借鉴过来的,如果看过之前的文章有关 Merkle-Damgård结构的介绍,会发现这个也是符合这个结构的,这里最后的输出就是一个单独的函数,而不是直接就输出最终的向量。

压缩函数构造

在任何一个哈希函数当中,压缩函数的构造都是整个算法的核心,对于Grøstl算法来说,它的压缩函数主要是通过两个置换函数来处理的,如下所示:

有关P和Q两个置换函数的介绍,咱们等会在讲(因为原来的论文他就是这么干的)。

输出转换

我们定义一个新的函数 表示一个n比特的串的末尾x比特,最终的输出函数 可以表示为:

【密码学】一文读懂Grøstl

P和Q的设计

对于P和Q的具体过程主要是分为如下的四步:

  • AddRoundConstant
  • SubBytes
  • ShiftBytes
  • MixBytes

看到这个,有没有莫名的熟悉感,如果没有,当我没说,这个和AES当中的轮函数是比较相似的,作者也说了,他的灵感也是来自于此,具体的函数定义如下:

下面来具体看一下这四步具体的过程

AddRoundConstant

这一步其实比较简单,实际上就是每个状态和某个常量进行一个异或操作

对于有关具体的轮常量的内容,读者们可以自行翻阅一下参考资料当中的论文,在这里我就不贴出来了,对于P和Q两个的轮常量是不一样的。

SubBytes

字节替代,这个和当时的AES是一样的,这里不熟悉的读者可以去翻一翻之前我写过的有关AES介绍的文章,这里也不过多的描述了。

ShiftBytes

对于这个过程,其实如果能理解了AES当中的行移位的操作,这个也不难理解,这里直接借用一下原始论文当中的图,因为这个图实在是不好画,我这里直接搬过来了。

【密码学】一文读懂Grøstl

实际上就是对状态矩阵的当中的每一个字节按照某个约定的移动位数,进行一次位置的变换操作。

MixBytes

这个运算同样是在有限域上的运算,有关于有限域的相关知识,可以去参考一下我之前写过的文章,如果说有不熟悉这方面知识的读者。这个有限域和AES取的有限域是一个,都是基于多项式 上的,这个变换实际上就是一个矩阵的乘法,如下所示

B矩阵的详细内容,这里我也不贴出来了,感兴趣的读者可以自行翻阅一下文末的参考资料。

补充

对于一个完整的哈希函数,介绍完了压缩函数,其实也就没啥了,我们来看一下剩余的部分,一个就是初始化项链,另一个就是padding,这两个好像也没啥能说的,初始化向量就是固定的常数值,padding在之前的哈希函数的介绍当中也介绍了不少了,在这里就不啰嗦了。

代码实现

这里回归老本行了,还是拿rust来写一下这个代码的实现吧,rust给的一个库是采用查表法来实现的,这里咱们还是用本文当中讲解的做法来写,咋感觉又给我挖了个坑呢,查表法下次一定把。

mod compress;
mod utils;

use crate::compress::{compress, PermutationType};

use core::fmt;
use std::array::from_ref;
use std::fmt::Formatter;
use digest::{block_buffer::Eager, core_api::{
    AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper,
    OutputSizeUser, UpdateCore,
}, typenum::{Unsigned, U128, U64}, HashMarker, Output, Reset};
use digest::core_api::FixedOutputCore;

#[derive(Clone)]
pub struct GroestlCore {
    block_len: u64,
    state: [u648],
}

impl HashMarker for GroestlCore {}

impl BlockSizeUser for GroestlCore {
    type BlockSize = U64;
}

impl BufferKindUser for GroestlCore {
    type BufferKind = Eager;
}

impl OutputSizeUser for GroestlCore {
    type OutputSize = U128;
}

impl UpdateCore for GroestlCore {
    #[inline]
    fn update_blocks(&mut self, blocks: &[Block<Self>]) {
        self.block_len = self.block_len.wrapping_add(blocks.len() as u64);
        compress(&mut self.state, convert(blocks));
    }
}

impl FixedOutputCore for GroestlCore {
    #[inline]
    fn finalize_fixed_core(&mut self, buffer: &mut Buffer<Self>, out: &mut Output<Self>) {
        let blocks_len = if buffer.remaining() <= 8 {
            self.block_len + 2
        } else {
            self.block_len + 1
        };

        buffer.len64_padding_be(blocks_len, |b| compress(&mut self.state, convert(from_ref(b))));
        let res = compress::round(self.state, PermutationType::P);
        self.state = compress::xor(&res, &self.state);
        let n = 4;
        for (chunk, v) in out.chunks_exact_mut(8).zip(self.state[n..].iter()) {
            chunk.copy_from_slice(&v.to_be_bytes());
        }
    }
}

impl Default for GroestlCore {
    #[inline]
    fn default() -> Self {
        Self {
            block_len: 0,
            state: [0000000256],
        }
    }
}

impl Reset for GroestlCore {
    #[inline]
    fn reset(&mut self) {
        *self = Default::default();
    }
}

impl AlgorithmName for GroestlCore {
    fn write_alg_name(f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("Grøstl")
    }
}

impl fmt::Debug for GroestlCore {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("Grøstl { ... }")
    }
}

/// Grøstl hasher state
pub type Groestl = CoreWrapper<GroestlCore>;

const BLOCK_SIZE: usize = <GroestlCore as BlockSizeUser>::BlockSize::USIZE;

#[inline(always)]
fn convert(blocks: &[Block<GroestlCore>]) -> &[[u8; BLOCK_SIZE]] {
    // SAFETY: GenericArray<u8, U64> and [u8; 64] have
    // exactly the same memory layout
    let p = blocks.as_ptr() as *const [u8; BLOCK_SIZE];
    unsafe { core::slice::from_raw_parts(p, blocks.len()) }
}

const SBOX: [u8256] = [
    0x630x7c0x770x7b0xf20x6b0x6f0xc50x300x010x670x2b0xfe0xd70xab0x76,
    0xca0x820xc90x7d0xfa0x590x470xf00xad0xd40xa20xaf0x9c0xa40x720xc0,
    0xb70xfd0x930x260x360x3f0xf70xcc0x340xa50xe50xf10x710xd80x310x15,
    0x040xc70x230xc30x180x960x050x9a0x070x120x800xe20xeb0x270xb20x75,
    0x090x830x2c0x1a0x1b0x6e0x5a0xa00x520x3b0xd60xb30x290xe30x2f0x84,
    0x530xd10x000xed0x200xfc0xb10x5b0x6a0xcb0xbe0x390x4a0x4c0x580xcf,
    0xd00xef0xaa0xfb0x430x4d0x330x850x450xf90x020x7f0x500x3c0x9f0xa8,
    0x510xa30x400x8f0x920x9d0x380xf50xbc0xb60xda0x210x100xff0xf30xd2,
    0xcd0x0c0x130xec0x5f0x970x440x170xc40xa70x7e0x3d0x640x5d0x190x73,
    0x600x810x4f0xdc0x220x2a0x900x880x460xee0xb80x140xde0x5e0x0b0xdb,
    0xe00x320x3a0x0a0x490x060x240x5c0xc20xd30xac0x620x910x950xe40x79,
    0xe70xc80x370x6d0x8d0xd50x4e0xa90x6c0x560xf40xea0x650x7a0xae0x08,
    0xba0x780x250x2e0x1c0xa60xb40xc60xe80xdd0x740x1f0x4b0xbd0x8b0x8a,
    0x700x3e0xb50x660x480x030xf60x0e0x610x350x570xb90x860xc10x1d0x9e,
    0xe10xf80x980x110x690xd90x8e0x940x9b0x1e0x870xe90xce0x550x280xdf,
    0x8c0xa10x890x0d0xbf0xe60x420x680x410x990x2d0x0f0xb00x540xbb0x16,
];

#[derive(Clone, Copy)]
pub enum PermutationType {
    P,
    Q,
}

fn pick_row(col: u64, i: usize) -> u8 {
    return ((col >> (8 * (7 - i))) & 0xFFas u8;
}


fn add_round_constant(mut state: [u648], r: usize, variant: PermutationType) -> [u648] {
    match variant {
        PermutationType::P => {
            let mut i = 0;
            let l = state.len();
            while i < l {
                state[i] ^= (((i << 4) ^ r) << (8 * 7)) as u64;
                i += 1;
            }
        }
        PermutationType::Q => {
            let mut i = 0;
            let l = state.len();
            while i < l {
                state[i] ^= ((!0) ^ ((i << 4) ^ r)) as u64;
                i += 1;
            }
        }
    }
    return state;
}

fn sub_bytes(mut state: [u648]) -> [u648] {
    let mut new_col = [0u88];
    let mut i = 0;
    let l = state.len();
    while i < l {
        for j in 0..8 {
            new_col[j] = SBOX[pick_row(state[i], j) as usize];
        }
        state[i] = new_col.iter().fold(0, |x, &i| x << 8 | i as u64);
        i += 1;
    }
    return state;
}

fn shift_bytes(state: [u648], variant: PermutationType) -> [u648] {
    let shift_vector = match variant {
        PermutationType::P => {
            [01234567]
        }
        PermutationType::Q => {
            [13570246]
        }
    };
    let l = state.len();
    let mut ret = [0u648];
    for i in 0..l {
        ret[i] = pick_row(state[(i + shift_vector[0]) % l], 0as u64;
        for j in 1..8 {
            ret[i] <<= 8;
            ret[i] ^= pick_row(state[(i + shift_vector[j]) % l], j) as u64;
        }
    }
    return ret;
}

fn gmul(ap: u8, bp: u8) -> u8 {
    let mut p = 0u8;
    let mut a = ap;
    let mut b = bp;
    while a != 0 && b != 0 {
        if b & 1 != 0 {
            p ^= a;
        }
        if a & 0x80 != 0 {
            // XOR with the primitive polynomial x^8 + x^4 + x^3 + x + 1 (0b1_0001_1011) – you can change it but it must be irreducible
            a = (((a << 1as u16) ^ 0x11bas u8;
        } else {
            a = a << 1;
        }
        b >>= 1;
    }
    return p & 0xFF;
}

fn mix_bytes(mut state: [u648]) -> [u648] {
    let mut temp = [08];
    for i in 0..state.len() {
        for j in 0..8 {
            temp[j] =
                gmul(pick_row(state[i], (j + 0) % 8), 2) ^
                    gmul(pick_row(state[i], (j + 1) % 8), 2) ^
                    gmul(pick_row(state[i], (j + 2) % 8), 3) ^
                    gmul(pick_row(state[i], (j + 3) % 8), 4) ^
                    gmul(pick_row(state[i], (j + 4) % 8), 5) ^
                    gmul(pick_row(state[i], (j + 5) % 8), 3) ^
                    gmul(pick_row(state[i], (j + 6) % 8), 5) ^
                    gmul(pick_row(state[i], (j + 7) % 8), 7);
        }
        state[i] = temp.iter().fold(0, |x, &i| x << 8 | i as u64);
    }
    return state;
}

pub fn round(mut state: [u648], variant: PermutationType) -> [u648] {
    for i in 0..10 {
        state = add_round_constant(state, i, variant);
        state = sub_bytes(state);
        state = shift_bytes(state, variant);
        state = mix_bytes(state);
    }
    return state;
}

pub fn xor(a: &[u648], b: &[u648]) -> [u648] {
    let mut out = [08];
    for i in 0..8 {
        out[i] = a[i] ^ b[i];
    }
    return out;
}

fn compress_block(state: &mut [u648], block: &[u648]) {
    // f(h,m) = P(h + m) + Q(m) + h
    let temp = round(xor(state, block), PermutationType::P);
    let q = round(block.clone(), PermutationType::Q);
    let temp = xor(&xor(&temp, &q), state);
    for i in 0..8 {
        state[i] = temp[i];
    }
}

fn build_columns(data: &[u864]) -> [u648] {
    let mut out = [08];
    for i in 0..8 {
        out[i] = (data[(i * 8)..(i * 8 + 8)]).iter().fold(0, |x, &i| x << 8 | i as u64);
    }
    return out;
}

pub fn compress(state: &mut [u648], blocks: &[[u864]]) {
    for block in blocks {
        compress_block(state, &build_columns(block));
    }
}

参考资料

  • http://www.groestl.info/
  • https://github.com/kacpal/groestl


原文始发于微信公众号(Coder小Q):【密码学】一文读懂Grøstl

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年8月27日23:46:19
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【密码学】一文读懂Grøstlhttps://cn-sec.com/archives/1257696.html

发表评论

匿名网友 填写信息