gpt4 book ai didi

rust - 为什么我在实现 HMAC-SHA256 时会得到不正确的值?

转载 作者:行者123 更新时间:2023-11-29 08:07:39 37 4
gpt4 key购买 nike

我正在尝试在 Rust 中创建一个函数,它将返回一个 HMAC-SHA256 摘要。我一直在根据 Wikipedia 的描述工作和 RFC 2104 .

我一直在努力返回正确的 HMAC。我正在使用 ring对于 SHA256 摘要,但无论我尝试什么,我似乎都无法获得正确的结果。我怀疑它可能与 .as_ref().to_vec() 转换有关。即使那是真的,我也不知道如何继续下去。并非 RFC 2104 中的所有内容都在以下代码中实现,但它突出了我的问题。

extern crate ring;
use ring::{digest, test};

pub fn hmac(k: Vec<u8>, mut m: Vec<u8>) -> Vec<u8> {
// Initialize ipad and opad as byte vectors with SHA256 blocksize
let ipad = vec![0x5C; 64];
let opad = vec![0x36; 64];
// iround and oround are used to seperate the two steps with XORing
let mut iround = vec![];
let mut oround = vec![];

for count in 0..k.len() {
iround.push(k[count] ^ ipad[count]);
oround.push(k[count] ^ opad[count]);
}

iround.append(&mut m); // m is emptied here
iround = (digest::digest(&digest::SHA256, &iround).as_ref()).to_vec();
oround.append(&mut iround); // iround is emptied here
oround = (digest::digest(&digest::SHA256, &oround).as_ref()).to_vec();
let hashed_mac = oround.to_vec();

return hashed_mac;
}

#[test]
fn test_hmac_digest() {
let k = vec![0x61; 64];
let m = vec![0x62; 64];
let actual = hmac(k, m);
// Expected value taken from: https://www.freeformatter.com/hmac-generator.html#ad-output
let expected = test::from_hex("f6cbb37b326d36f2f27d294ac3bb46a6aac29c1c9936b985576041bfb338ae70").unwrap();
assert_eq!(actual, expected);
}

这些是摘要:

Actual = [139, 141, 144, 52, 11, 3, 48, 112, 117, 7, 56, 151, 163, 65, 152, 195, 163, 164, 26, 250, 178, 100, 187, 230, 89, 61, 191, 164, 146, 228, 180, 62]

Expected = [246, 203, 179, 123, 50, 109, 54, 242, 242, 125, 41, 74, 195, 187, 70, 166, 170, 194, 156, 28, 153, 54, 185, 133, 87, 96, 65, 191, 179, 56, 174, 112]

最佳答案

正如评论中提到的,您已经交换了内部和外部填充的字节。返回引用 Wikipedia page :

o_key_pad = key xor [0x5c * blockSize]   //Outer padded key
i_key_pad = key xor [0x36 * blockSize] //Inner padded key

这是我对该功能的看法。我相信它的分配较少:

extern crate ring;

use ring::{digest, test};

const BLOCK_SIZE: usize = 64;

pub fn hmac(k: &[u8], m: &[u8]) -> Vec<u8> {
assert_eq!(k.len(), BLOCK_SIZE);

let mut i_key_pad: Vec<_> = k.iter().map(|&k| k ^ 0x36).collect();
let mut o_key_pad: Vec<_> = k.iter().map(|&k| k ^ 0x5C).collect();

i_key_pad.extend_from_slice(m);

let hash = |v| digest::digest(&digest::SHA256, v);

let a = hash(&i_key_pad);

o_key_pad.extend_from_slice(a.as_ref());

hash(&o_key_pad).as_ref().to_vec()
}

#[test]
fn test_hmac_digest() {
let k = [0x61; BLOCK_SIZE];
let m = [0x62; BLOCK_SIZE];
let actual = hmac(&k, &m);

// Expected value taken from: https://www.freeformatter.com/hmac-generator.html#ad-output
let expected = test::from_hex("f6cbb37b326d36f2f27d294ac3bb46a6aac29c1c9936b985576041bfb338ae70").unwrap();
assert_eq!(actual, expected);
}

关于rust - 为什么我在实现 HMAC-SHA256 时会得到不正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630814/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com