/* 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"

ssize_t
GNUNET_REHASH_data_for_mapping (
  enum GNUNET_REHASH_Hash_Type out_type,
  enum GNUNET_REHASH_Hash_Type in_type,
  const char *out_data,
  const char *in_data,
  size_t out_size,
  size_t in_size,
  char *dest,
  size_t dest_size)
{
  struct GNUNET_HashCode clear_query;
  struct GNUNET_CRYPTO_SymmetricSessionKey skey;
  struct GNUNET_CRYPTO_SymmetricInitializationVector iv;

  /* Buffer size (and overflow prevention) check*/
  if (out_size > 64)
    return -1;
  if (dest_size < out_size)
    return -1;

  /* 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 -1;
  GNUNET_CRYPTO_hash_to_aes_key (&clear_query, &skey, &iv);

  /* Encrypt @a out_data with skey and iv */
  if (out_size != GNUNET_CRYPTO_symmetric_encrypt
    (out_data, out_size, &skey, &iv, dest))
    return -1;

  return out_size;
}
