【问题标题】:HMAC-SHA1 in RustRust 中的 HMAC-SHA1
【发布时间】:2019-07-04 07:11:16
【问题描述】:

我正在尝试应用 HMAC-SHA1 以检查某些内容,但我无法使其正常工作。

这些是我的测试:

#[cfg(test)]
mod tests {

    use crypto::hmac::Hmac;
    use crypto::mac::Mac;

    use crypto::sha1::Sha1;
    use std::str::from_utf8;

    const BODY_CONTENT: &'static str = r#"bodystring"#;
    const KEY: &[u8] = b"secret_key";
    const COMPUTED_HMAC: &'static str = "97049623b0e5d20bf6beb5313d80600e3d6abe56";

    #[test]
    fn test_hmac_sha1() {
        let mut mac= Hmac::new(Sha1::new(), KEY);
        mac.input(BODY_CONTENT.as_bytes());
        let result = mac.result();
        let code = result.code();
        assert_eq!(COMPUTED_HMAC.as_bytes(), code);
        assert_eq!(COMPUTED_HMAC, from_utf8(&code).unwrap_or("failed"));
    }

    #[test]
    fn test_hmac_sha1_direct() {
        let hash = hmacsha1::hmac_sha1(KEY, BODY_CONTENT.as_bytes());
        assert_eq!(COMPUTED_HMAC.as_bytes(), hash);
        assert_eq!(COMPUTED_HMAC, from_utf8(&hash).unwrap_or("failed"));
    }
}

我已使用此website 来获取COMPUTED_HMAC,方法是使用一个字符串 (BODY_CONTENT) 和一个密钥 (KEY)。

如您所见,我正在尝试同时利用 rust-cryptohmac-sha1 板条箱,并且我对它们都获得了相同的结果。

问题是这个结果与我在网站 (97049623b0e5d20bf6beb5313d80600e3d6abe56) 上得到的结果不匹配,并且测试失败了。您可能认为该网站是错误的,但事实并非如此,因为我使用它来验证 Github 生成的其他一些哈希(我正在使用 Github 应用程序)并且它有效。

那么,很明显,我在这里遗漏了一些步骤,但我无法弄清楚,非常感谢您的帮助。

【问题讨论】:

    标签: rust cryptography hmac hmacsha1


    【解决方案1】:

    返回了正确的哈希值,它只是不是您期望的表示形式。哈希作为原始字节返回,而不是作为转换为 ASCII 十六进制数字的字节。

    如果我们将哈希码数组打印为十六进制,如下所示:

    println!("{:02x?}", code);
    

    然后我们可以看到它与您的字符串匹配:

    [97, 04, 96, 23, b0, e5, d2, 0b, f6, be, b5, 31, 3d, 80, 60, 0e, 3d, 6a, be, 56]
    // 97049623b0e5d20bf6beb5313d80600e3d6abe56
    

    而字符串 "97049623b0e5d20bf6beb5313d80600e3d6abe56" 看起来像这样:

    [39, 37, 30, 34, 39, 36, 32, 33, 62, 30, 65, 35, 64, 32, 30, 62, 66, 36, 62, 65,
     62, 35, 33, 31, 33, 64, 38, 30, 36, 30, 30, 65, 33, 64, 36, 61, 62, 65, 35, 36]
    

    使用itertools,我们可以像这样将前者转换为后者:

    assert_eq!(
        COMPUTED_HMAC,
        code.iter().format_with("", |byte, f| f(&format_args!("{:02x}", byte))).to_string());
    

    【讨论】:

    • 感谢您的回答!我在兜圈子。最后,按照您的建议将生成的哈希编码为十六进制效果很好。我使用base16 对其进行编码。
    【解决方案2】:

    感谢弗朗西斯和罗伯特,这段代码对我有用。

    code.iter().map(|b| format!("{:02x}", b)).collect::<Vec<_>>().join("")
    

    该行返回:“97049623b0e5d20bf6beb5313d80600e3d6abe56”作为字符串

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 2012-10-12
      • 2011-01-28
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多