/*************************************************
* HMAC Header File                               *
* (C) 1999-2002 The OpenCL Project               *
*************************************************/

#ifndef OPENCL_HMAC_H__
#define OPENCL_HMAC_H__

#include <opencl/opencl.h>

namespace OpenCL {

template<typename H>
class HMAC : public MessageAuthenticationCode
   {
   public:
      void clear() throw();
      std::string name() const { return "HMAC<" + hash->name() + ">"; }
      MessageAuthenticationCode* clone() const { return new HMAC<H>; }
      HMAC(HashFunction* = new H);
      ~HMAC() { delete hash; }
   private:
      void add_data(const byte[], u32bit);
      void final_result(byte[]);
      void key(const byte[], u32bit);
      HashFunction* hash;
      SecureVector<byte> i_key, o_key;
   };

/*************************************************
* Update an HMAC Calculation                     *
*************************************************/
template<typename H>
void HMAC<H>::add_data(const byte input[], u32bit length)
   {
   hash->update(input, length);
   }

/*************************************************
* Finalize a HMAC Calculation                    *
*************************************************/
template<typename H>
void HMAC<H>::final_result(byte mac[])
   {
   hash->final(mac);
   hash->update(o_key, o_key.size());
   hash->update(mac, OUTPUT_LENGTH);
   hash->final(mac);
   hash->update(i_key, i_key.size());
   }

/*************************************************
* HMAC Key Setup                                 *
*************************************************/
template<typename H>
void HMAC<H>::key(const byte key[], u32bit length)
   {
   hash->clear();
   i_key.set(0x36);
   o_key.set(0x5C);

   SecureVector<byte> hmac_key(key, length);
   if(length > hash->HASH_BLOCK_SIZE)
      hmac_key = hash->process(key, length);

   xor_buf(i_key, hmac_key, hmac_key.size());
   xor_buf(o_key, hmac_key, hmac_key.size());
   hash->update(i_key, i_key.size());
   }

/*************************************************
* Clear memory of sensitive data                 *
*************************************************/
template<typename H>
void HMAC<H>::clear() throw()
   {
   hash->clear();
   i_key.clear();
   o_key.clear();
   }

/*************************************************
* Clear memory of sensitive data                 *
*************************************************/
template<typename H>
HMAC<H>::HMAC(HashFunction* h) :
   MessageAuthenticationCode(h->OUTPUT_LENGTH, 1, 32), hash(h)
   {
   if(hash->HASH_BLOCK_SIZE == 0)
      throw Invalid_Argument("HMAC cannot be used with " + hash->name());
   i_key.create(hash->HASH_BLOCK_SIZE);
   o_key.create(hash->HASH_BLOCK_SIZE);
   }

}

#endif
