HMAC <sha256>的结果与另一个实现不同

时间:2018-07-31 17:35:23

标签: cryptography rust sha256 hmac

我正在尝试使用SHA256与API交互来实现HMAC验证。我发现了hmacsha2板条箱,根据它们的示例,它们可以完美地满足我的目的。

我有此代码:

extern crate hmac;
extern crate sha2;

use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

pub fn verify(message: &[u8], code: &[u8], key: &[u8]) -> bool {
    type HmacSha256 = Hmac<Sha256>;

    let mut mac = HmacSha256::new_varkey(key).unwrap();
    mac.input(message);

    let result = mac.result().code();
    return result == code;
}

#[cfg(test)]
mod tests {
    use verify;
    #[test]
    fn should_work() {
        assert!(verify(
          b"code=0907a61c0c8d55e99db179b68161bc00&shop=some-shop.myshopify.com&timestamp=1337178173",
          b"4712bf92ffc2917d15a2f5a273e39f0116667419aa4b6ac0b3baaf26fa3c4d20",
          b"hush"
        ), "Returned false with correct parameters!");
    }

    #[test]
    fn shouldnt_work() {
        assert!(
            !verify(
                b"things=things&stuff=this_is_pod_racing",
                b"3b3f62798a09c78hjbjsakbycut^%9n29ddeb8f6862b42c7eb6fa65cf2a8cade",
                b"mysecu)reAn111eecretB"
            ),
            "Returned true with incorrect parameters!"
        );
    }
}

cargo test应该显示有效的HMAC验证,而无效。

不幸的是,verify函数给出的结果与在线HMAC生成器的结果不一致。例如,使用消息code=0907a61c0c8d55e99db179b68161bc00&shop=some-shop.myshopify.com&timestamp=1337178173和密钥hush,此online HMAC生成器指示哈希应为4712bf92ffc2917d15a2f5a273e39f0116667419aa4b6ac0b3baaf26fa3c4d20,但这导致我的测试失败并打印出来结果确认哈希不正确。

我已经确认我的字节字符串文字的结果确实是它们的ASCII等效项,否则我将执行该过程,几乎完全像示例所示。

由于侧通道攻击,最终版本中我将不会使用result == code,这只是为了使调试工作变得更轻松。

Cargo.toml

[package]
name = "crypto"
version = "0.1.0"


[dependencies]
hmac = "0.6.2"
sha2 = "0.7.1"

1 个答案:

答案 0 :(得分:4)

  
4712bf92ffc2917d15a2f5a273e39f0116667419aa4b6ac0b3baaf26fa3c4d20

不应将其视为ASCII字节串。这是原始字节的十六进制编码为易于人类阅读的格式。您需要正确匹配编码:

extern crate hmac;
extern crate sha2;
extern crate hex;

use hmac::{Hmac, Mac};
use sha2::Sha256;

pub fn verify(message: &[u8], code: &str, key: &[u8]) -> bool {
    type HmacSha256 = Hmac<Sha256>;

    let mut mac = HmacSha256::new_varkey(key).unwrap();
    mac.input(message);

    let result = mac.result().code();

    let r2 = hex::encode(&result);

    r2 == code
}

#[test]
fn should_work() {
    assert!(verify(
        b"code=0907a61c0c8d55e99db179b68161bc00&shop=some-shop.myshopify.com&timestamp=1337178173",
        "4712bf92ffc2917d15a2f5a273e39f0116667419aa4b6ac0b3baaf26fa3c4d20",
        b"hush"
    ), "Returned false with correct parameters!");
}

#[test]
fn shouldnt_work() {
    assert!(
        !verify(
            b"things=things&stuff=this_is_pod_racing",
            "3b3f62798a09c78hjbjsakbycut^%9n29ddeb8f6862b42c7eb6fa65cf2a8cade",
            b"mysecu)reAn111eecretB"
        ),
        "Returned true with incorrect parameters!"
    );
}

另请参阅: