Skip to content

Truly independent web browser

2.3 KB
Raw Blame
/*
 * Copyright (c) 2021-present, the Ladybird developers.
 * Copyright (c) 2025, Altomani Gianluca <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCrypto/Authentication/HMAC.h>
#include <LibTest/TestCase.h>

static ByteBuffer operator""_b(char const* string, size_t length)
{
    return MUST(ByteBuffer::copy(string, length));
}

TEST_CASE(test_hmac_sha256_process)
{
    auto key = "Well Hello Friends"_b;
    u8 result[] {
        0x1a, 0xf2, 0x20, 0x62, 0xde, 0x3b, 0x84, 0x65, 0xc1, 0x25, 0x23, 0x99, 0x76, 0x15, 0x1b, 0xec, 0x15, 0x21, 0x82, 0x1f, 0x23, 0xca, 0x11, 0x66, 0xdd, 0x8c, 0x6e, 0xf1, 0x81, 0x3b, 0x7f, 0x1b
    };
    auto mac = TRY_OR_FAIL(Crypto::Authentication::hmac(Crypto::Hash::HashKind::SHA256, key, "Some bogus data"sv.bytes()));
    EXPECT_EQ(mac.bytes(), ReadonlyBytes { result });
}

TEST_CASE(test_hmac_sha256_data_is_same_size_as_block)
{
    auto key = "Well Hello Friends"_b;
    u8 result[] = {
        0x1d, 0x90, 0xce, 0x68, 0x45, 0x0b, 0xba, 0xd6, 0xbe, 0x1c, 0xb2, 0x3a, 0xea, 0x7f, 0xac, 0x4b, 0x68, 0x08, 0xa4, 0x77, 0x81, 0x2a, 0xad, 0x5d, 0x05, 0xe2, 0x15, 0xe8, 0xf4, 0xcb, 0x06, 0xaf
    };
    auto mac = TRY_OR_FAIL(Crypto::Authentication::hmac(Crypto::Hash::HashKind::SHA256, key, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"sv.bytes()));
    EXPECT_EQ(mac.bytes(), ReadonlyBytes { result });
}

TEST_CASE(test_hmac_sha256_data_is_bigger_size_as_block)
{
    auto key = "Well Hello Friends"_b;
    u8 result[] = {
        0x9b, 0xa3, 0x9e, 0xf3, 0xb4, 0x30, 0x5f, 0x6f, 0x67, 0xd0, 0xa8, 0xb0, 0xf0, 0xcb, 0x12, 0xf5, 0x85, 0xe2, 0x19, 0xba, 0x0c, 0x8b, 0xe5, 0x43, 0xf0, 0x93, 0x39, 0xa8, 0xa3, 0x07, 0xf1, 0x95
    };
    auto mac = TRY_OR_FAIL(Crypto::Authentication::hmac(Crypto::Hash::HashKind::SHA256, key, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"sv.bytes()));
    EXPECT_EQ(mac.bytes(), ReadonlyBytes { result });
}

TEST_CASE(test_hmac_sha256_empty_key)
{
    u8 result[] {
        0xb6, 0x13, 0x67, 0x9a, 0x08, 0x14, 0xd9, 0xec, 0x77, 0x2f, 0x95, 0xd7, 0x78, 0xc3, 0x5f, 0xc5, 0xff, 0x16, 0x97, 0xc4, 0x93, 0x71, 0x56, 0x53, 0xc6, 0xc7, 0x12, 0x14, 0x42, 0x92, 0xc5, 0xad
    };
    auto mac = TRY_OR_FAIL(Crypto::Authentication::hmac(Crypto::Hash::HashKind::SHA256, {}, {}));
    EXPECT_EQ(mac.bytes(), ReadonlyBytes { result });
}