/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2024-2025 Brett A C Sheffield <bacs@librecast.net> */

#include "test.h"
#include <key.h>

/* see https://doc.libsodium.org/public-key_cryptography/authenticated_encryption */
#define MESSAGE (const unsigned char *) "test"
#define MESSAGE_LEN 4
#define CIPHERTEXT_LEN (crypto_box_MACBYTES + MESSAGE_LEN)
int verify_crypto_key(unsigned char *public, unsigned char *secret)
{
	unsigned char nonce[crypto_box_NONCEBYTES];
	unsigned char ciphertext[CIPHERTEXT_LEN];
	int rc;

	randombytes_buf(nonce, sizeof nonce);
	rc = crypto_box_easy(ciphertext, MESSAGE, MESSAGE_LEN, nonce, public, secret);
	if (!test_assert(rc == 0, "crypto_secretbox_easy()")) return test_status;

	unsigned char decrypted[MESSAGE_LEN];
	rc = crypto_box_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, public, secret);
	test_assert(rc == 0, "decrypt message");
	return test_status;
}

int main(void)
{
	key_combo_t keyring;
	char name[] = "key_gen_keys() - verify encryption keypair";
	int rc;

	test_name(name);

	rc = key_gen_keys(&keyring);
	test_assert(rc == 0, "key_gen_keys()");

	/* verify the first part of the key is an encryption key */
	if (verify_crypto_key(keyring.e.pk, keyring.e.sk)) return test_status;

	return 0;
}
