/* GNU Guix --- Functional package management for GNU
   Copyright © 2020 Maxime Devos <maxime.devos@student.kuleuven.be>

   This file is part of GNU Guix.

   GNU Guix is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or (at
   your option) any later version.

   GNU Guix is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>. */

#include <gnunet/gnunet_config.h>
#include <gnunet/gnunet_crypto_lib.h>
#include <stdint.h>
#include "rehash_crypto.h"

int
GNUNET_REHASH_mapping_for_data (
  enum GNUNET_REHASH_Hash_Type out_type,
  enum GNUNET_REHASH_Hash_Type in_type,
  const char *in_data,
  size_t in_size,
  const char *dht_data,
  size_t dht_size,
  char *cleartext)
{
  struct GNUNET_HashCode clear_query;
  struct GNUNET_CRYPTO_SymmetricSessionKey skey;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;

  /* Buffer size (and overflow prevention) check.
     In practice, hash length is rather limited.
     Future hashes may require more bytes. */
  if (dht_size > 64)
    return GNUNET_NO;

  /* Derive an encryption key from cleartext query */
  if (GNUNET_OK != GNUNET_REHASH_cleartext_query_from_hash
        (out_type, in_type, in_data, in_size, &clear_query))
    return GNUNET_NO;
  GNUNET_CRYPTO_hash_to_aes_key (&clear_query, &skey, &iv);

  /* Seems OK, decrypt */
  if ((ssize_t) dht_size != GNUNET_CRYPTO_symmetric_decrypt
    (dht_data, dht_size, &skey, &iv, cleartext))
    return GNUNET_NO;

  return GNUNET_OK;
}
