/**
 * \file      test-mac-hmac-md5.c
 *
 * \brief     The HMAC-MD5 message authentication code unit-tests
 *
 * \warning   MD5 is considered a weak message digest and its use constitutes a
 *            security risk! We recommend considering stronger message digests
 *            instead!
 *
 * \copyright 2022 Joseph Benden <joe@benden.us>
 *
 * \license   GPL-2.0-OR-LATER
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>

#include "aircrack-ng/crypto/crypto.h"
#include "tests.h"

// clang-format off
/*
 * RFC 2202 test vectors
 */
struct {
	uint8_t         key[96];
	size_t          key_len;
	uint8_t         data[96];
	size_t          data_len;
	uint8_t         digest[DIGEST_MD5_MAC_LEN];
} md5_tests[] = {
	{
		{0x0b, 0x0b, 0x0b, 0x0b,
		 0x0b, 0x0b, 0x0b, 0x0b,
		 0x0b, 0x0b, 0x0b, 0x0b,
		 0x0b, 0x0b, 0x0b, 0x0b},
		16,
		"Hi There",
		8,
		{0x92, 0x94, 0x72, 0x7a,
		 0x36, 0x38, 0xbb, 0x1c,
		 0x13, 0xf4, 0x8e, 0xf8,
		 0x15, 0x8b, 0xfc, 0x9d}
	},
	{
		"Jefe",
		4,
		"what do ya want for nothing?",
		28,
		{0x75, 0x0c, 0x78, 0x3e,
		 0x6a, 0xb0, 0xb5, 0x03,
		 0xea, 0xa8, 0x6e, 0x31,
		 0x0a, 0x5d, 0xb7, 0x38}
#ifdef EXPENSIVE_TESTS
	},
	{
		{0xaa, 0xaa, 0xaa, 0xaa,
		 0xaa, 0xaa, 0xaa, 0xaa,
		 0xaa, 0xaa, 0xaa, 0xaa,
		 0xaa, 0xaa, 0xaa, 0xaa},
		16,
		{0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
		 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
		 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xd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aa, 0xaa, 0xaa, 0xaa,
		 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, //64
		 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
		 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, //80
		80,
		"Test Using Larger Than Block-Size Key and "
		"Larger Than One Block-Size Data",
		73,
		{0x6f, 0x63, 0x0f, 0xad,
		 0x67, 0xcd, 0xa0, 0xee,
		 0x1f, 0xb1, 0xf5, 0x62,
		 0xdb, 0x3a, 0xa5, 0x3e}
#endif
	}
};
// clang-format on

STATIC_ASSERT(ArrayCount(md5_tests) >= 2u, ensure_at_least_2_entries);

int main(int argc, char ** argv)
{
	size_t i;
	int error = 0;
	uint8_t md5sum[DIGEST_MD5_MAC_LEN];

	(void) argc;

	for (i = 0; i < ArrayCount(md5_tests); i++)
	{
		error |= MAC_HMAC_MD5(md5_tests[i].key_len,
							  md5_tests[i].key,
							  md5_tests[i].data_len,
							  md5_tests[i].data,
							  md5sum);
		error |= test(md5sum, md5_tests[i].digest, DIGEST_MD5_MAC_LEN, argv[0]);
	}

	for (i = 0; i < ArrayCount(md5_tests); i++)
	{
		error |= MAC_HMAC_MD5_Vector(
			md5_tests[i].key_len,
			md5_tests[i].key,
			1,
			(const uint8_t * []){(uint8_t *) &md5_tests[i].data},
			&md5_tests[i].data_len,
			md5sum);
		error |= test(md5sum, md5_tests[i].digest, DIGEST_MD5_MAC_LEN, argv[0]);
	}

	return error;
}
