ETSI STF525 / Internal Testing test suite
This project provides an internal testing test suite and its associated Test Adapter/Codec
hmac.hh
Go to the documentation of this file.
1 
11 #pragma once
12 
13 #include <vector>
14 
15 #include <openssl/hmac.h>
16 #include <openssl/objects.h>
17 
21 enum class hash_algorithms: unsigned char {
22  sha_256,
23  sha_384
24 }; // End of class hash_algorithms
25 
26 
31 class hmac {
32  HMAC_CTX _ctx;
34 public:
40  hmac(const hash_algorithms p_hash_algorithms): _ctx{}, _hash_algorithms(p_hash_algorithms) { ::HMAC_CTX_init(&_ctx); };
44  virtual ~hmac() { ::HMAC_CTX_cleanup(&_ctx); };
45 
55  inline int generate(const std::vector<unsigned char> p_buffer, const std::vector<unsigned char> p_secret_key, std::vector<unsigned char>& p_hmac) {
56  // Sanity check
57  if (p_buffer.size() == 0) {
58  return -1;
59  }
60 
61  return generate(p_buffer.data(), p_buffer.size(), p_secret_key.data(), p_secret_key.size(), p_hmac);
62  };
63 
75  inline int generate(const unsigned char *p_buffer, const size_t p_buffer_length, const unsigned char *p_secret_key, const size_t p_secret_key_length, std::vector<unsigned char>& p_hmac) {
76  // Sanity check
77  if ((p_buffer == nullptr) || (p_secret_key == nullptr)) {
78  return -1;
79  }
80 
81  if (_hash_algorithms == hash_algorithms::sha_256) {
82  p_hmac.resize(64);
83  ::HMAC_Init_ex(&_ctx, (const void*)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha256(), NULL);
84  } else if (_hash_algorithms == hash_algorithms::sha_384) {
85  p_hmac.resize(128);
86  ::HMAC_Init_ex(&_ctx, (const void*)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha384(), NULL);
87  } else { // TODO To be continued
88  return -1;
89  }
90  // Compute the hash value
91  ::HMAC_Update(&_ctx, p_buffer, p_buffer_length);
92  unsigned int length = p_hmac.size();
93  ::HMAC_Final(&_ctx, static_cast<unsigned char*>(p_hmac.data()), &length);
94  return 0;
95  };
96 }; // End of class hmac
hmac(const hash_algorithms p_hash_algorithms)
Default constructor Create a new instance of the hmac class.
Definition: hmac.hh:40
HMAC_CTX _ctx
Definition: hmac.hh:32
hash_algorithms
Definition: hmac.hh:21
int generate(const std::vector< unsigned char > p_buffer, const std::vector< unsigned char > p_secret_key, std::vector< unsigned char > &p_hmac)
Receive bytes formated data from the lower layers.
Definition: hmac.hh:55
This class provides description of HMAC helper methods.
Definition: hmac.hh:31
int generate(const unsigned char *p_buffer, const size_t p_buffer_length, const unsigned char *p_secret_key, const size_t p_secret_key_length, std::vector< unsigned char > &p_hmac)
Receive bytes formated data from the lower layers.
Definition: hmac.hh:75
virtual ~hmac()
Default destructor.
Definition: hmac.hh:44
hash_algorithms _hash_algorithms
HMAC context.
Definition: hmac.hh:33