/*!
 * \file      sha256.hh
 * \brief     Header file for SHA-256 helper methods.
 * \author    ETSI STF525
 * \copyright ETSI Copyright Notification
 *            No part may be reproduced except as authorized by written permission.
 *            The copyright and the foregoing restriction extend to reproduction in all media.
 *            All rights reserved.
 * \version   0.1
 */
#pragma once

#include <vector>

#include <openssl/sha.h>
#include <openssl/objects.h>

/*!
 * \class sha256
 * \brief  This class provides description of SHA-256 helper methods
 */
class sha256 {
  SHA256_CTX _ctx; //! SHA context
public:
  /*!
   * \brief Default constructor
   *        Create a new instance of the sha256 class
   */
  explicit sha256(): _ctx{} { };
  /*!
   * \brief Default destructor
   */
  virtual ~sha256() { };

  /*!
   * \inline
   * \fn int generate(const std::vector<unsigned char> p_buffer, std::vector<unsigned char>& p_hash);
   * \brief Receive bytes formated data from the lower layers
   * \param[in] p_buffer The data used to generate the SHA-256 hash
   * \param[out] p_hash The SHA-256 hash value based of the provided data
   * \return 0 on success, -1 otherwise
   */
  inline int generate(const std::vector<unsigned char> p_buffer, std::vector<unsigned char>& p_hash) {
    // Sanity check
    if (p_buffer.size() == 0) {
      return -1;
    }

    return generate(p_buffer.data(), p_buffer.size(), p_hash);
  };
  
  /*!
   * \inline
   * \fn int generate(const std::vector<unsigned char> p_buffer, std::vector<unsigned char>& p_hash);
   * \brief Receive bytes formated data from the lower layers
   * \param[in] p_buffer The data used to generate the SHA-256 hash
   * \param[in] The length of the data buffer
   * \param[out] p_hash The SHA-256 hash value based of the provided data
   * \return 0 on success, -1 otherwise
   */
  inline int generate(const unsigned char *p_buffer, const size_t p_length, std::vector<unsigned char>& p_hash) {
    // Sanity check
    if (p_buffer == nullptr) {
      return -1;
    }
    // Resize data buffer
    p_hash.resize(SHA256_DIGEST_LENGTH);
    // Compute the hash value
    ::SHA256_Init(&_ctx);
    ::SHA256_Update(&_ctx, p_buffer, p_length);
    ::SHA256_Final(static_cast<unsigned char*>(p_hash.data()), &_ctx);
    return 0;
  };
}; // End of class sha256
