Home > Back-end >  Are System.Security.Cryptography.HMAC classes not working properly?
Are System.Security.Cryptography.HMAC classes not working properly?

Time:06-22

I have to provide a hashed value response using HMAC with MD5 key. The problem is that HMACMD5 class is computing unexpected values.

Following code should assert that value expected is equal to actual.

        [Test]
        public void should()
        {
            var key = Encoding.UTF8.GetBytes("foobarsecret42");
            var hmac = new HMACMD5(key);
            var expected = "4c7bd5ae85894f78eb87bd2955f4cd83";

            var actual = hmac.ComputeHash(Convert.FromHexString(
                        "fdfeefeaa33d4f683bc843cae4375592439fa980ac969e7757226baf15ef5398"));

            Convert.ToHexString(actual).ToLower().Should().Be(expected);
        }

I have tested it with multiple Encodings and it is still failing to create proper hash. I also verified that those values (for assertion) are correct on https://www.freeformatter.com/ and also with some code written in Rust below.

use hmac::{Hmac, Mac};
use md5::Md5;
use hex_literal::hex;

fn main() {
    type HmacMd5 = Hmac<Md5>;
    let mut mac = HmacMd5::new_from_slice(b"foobarsecret42").unwrap();
    Mac::update(&mut mac,b"fdfeefeaa33d4f683bc843cae4375592439fa980ac969e7757226baf15ef5398");
    let result = mac.finalize();
    let bytes = result.into_bytes();
    let expected = hex!("4c7bd5ae85894f78eb87bd2955f4cd83");
    assert_eq!(bytes[..], expected[..]);
}

CodePudding user response:

The data fd...98 are neither hex decoded in the Rust code nor in the online tool, but UTF-8 (or ASCII) encoded in both cases. If this is also done in the C# code, i.e. with

var actual = hmac.ComputeHash(Encoding.UTF8.GetBytes("fdfeefeaa33d4f683bc843cae4375592439fa980ac969e7757226baf15ef5398"));

the expected value results.

  • Related