/* 1. ML-DSA sign and verify with the empty context string.
   2. The second (mode) parameter of GCRY_KDF_HKDF.  */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gcrypt.h>

static void
check (gcry_error_t e)
{
  if (e)
    {
      fprintf (stderr, "setup failed: %s\n", gcry_strerror (e));
      exit (1);
    }
}

static void
report (const char *what, gcry_error_t e)
{
  printf ("  %-36s %s\n", what, e ? gcry_strerror (e) : "ok");
}

static void
mldsa (void)
{
  static const unsigned char seed[32], msg[] = "message";
  unsigned char mprime[2 + sizeof msg] = { 0, 0 };
  gcry_sexp_t parm, pair, sk, pk, plain, empty, noprefix, sig, bad;

  memcpy (mprime + 2, msg, sizeof msg);
  check (gcry_sexp_build (&parm, NULL, "(genkey(dilithium3(S%b)))",
                          (int) sizeof seed, seed));
  check (gcry_pk_genkey (&pair, parm));
  sk = gcry_sexp_find_token (pair, "private-key", 0);
  pk = gcry_sexp_find_token (pair, "public-key", 0);

  check (gcry_sexp_build (&plain, NULL, "(data(raw)(value%b))",
                          (int) sizeof msg, msg));
  check (gcry_sexp_build (&empty, NULL, "(data(raw)(label%b)(value%b))",
                          0, "", (int) sizeof msg, msg));
  /* M' = 0 || 0 || M, FIPS 204 algorithm 2 with an empty context.  */
  check (gcry_sexp_build (&noprefix, NULL,
                          "(data(raw)(flags no-prefix)(value%b))",
                          (int) sizeof mprime, mprime));

  report ("sign, no label", gcry_pk_sign (&bad, plain, sk));
  report ("sign, empty label", gcry_pk_sign (&bad, empty, sk));
  check (gcry_pk_sign (&sig, noprefix, sk));
  report ("verify, no-prefix", gcry_pk_verify (sig, noprefix, pk));
  report ("verify, no label", gcry_pk_verify (sig, plain, pk));
  report ("verify, empty label", gcry_pk_verify (sig, empty, pk));
}

static void
hkdf (void)
{
  static const unsigned char ikm[32] = { 1 }, salt[32] = { 2 };
  unsigned char out[2][32];
  unsigned long mode;

  for (mode = 0; mode < 2; mode++)
    {
      unsigned long param[2] = { 32, 0 };
      gcry_kdf_hd_t h;

      param[1] = mode;
      check (gcry_kdf_open (&h, GCRY_KDF_HKDF, GCRY_MAC_HMAC_SHA256,
                            param, 2, ikm, sizeof ikm, salt, sizeof salt,
                            NULL, 0, NULL, 0));
      check (gcry_kdf_compute (h, NULL));
      check (gcry_kdf_final (h, sizeof out[mode], out[mode]));
      gcry_kdf_close (h);
    }
  printf ("  mode 0 and mode 1 accepted, output %s\n",
          memcmp (out[0], out[1], 32) ? "differs" : "identical");
}

int
main (void)
{
  printf ("libgcrypt %s\n", gcry_check_version (NULL));
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  printf ("ML-DSA-65:\n");
  mldsa ();
  printf ("HKDF:\n");
  hkdf ();
  return 0;
}
