#include <string.h>

#include "crypto.h"
#include "crypto-internal.h"

void
sigsum_hash_key (struct sigsum_hash *kh, const struct sigsum_pubkey *key)
{
  struct sigsum_hash_ctx ctx;
  _sigsum_hash_init (&ctx);
  _sigsum_hash_update (&ctx, sizeof (key->k), key->k);
  _sigsum_hash_digest (&ctx, kh);
}

size_t
sigsum_keyhash_lookup (size_t n, const struct sigsum_key_with_hash *keys,
		       const struct sigsum_hash *key_hash)
{
  size_t i;

  /* Do a linear search for a hash with matching first byte. In the
     typical case, there will only be a single iteration of the below
     memcmp loop. Could be changed to use binary search, but that is
     likely overkill. */
  for (i = 0; i < n && keys[i].hash.h[0] < key_hash->h[0]; i++)
    ;
  for (; i < n; i++)
    {
      int c = memcmp (keys[i].hash.h, key_hash->h, sizeof (key_hash->h));
      if (!c)
	return i;
      if (c > 0)
	break;
    }
  return (size_t) -1;
}
