IXWebSocket/ixcrypto/ixcrypto/IXHMac.cpp

54 lines
1.5 KiB
C++
Raw Normal View History

/*
* IXHMac.h
* Author: Benjamin Sergeant
* Copyright (c) 2018 Machine Zone. All rights reserved.
*/
#include "IXHMac.h"
2020-04-21 07:59:20 +02:00
2018-11-13 02:56:59 +01:00
#include "IXBase64.h"
2019-09-10 23:05:07 +02:00
#if defined(IXCRYPTO_USE_MBED_TLS)
2020-04-21 07:59:20 +02:00
#include <mbedtls/md.h>
#elif defined(__APPLE__)
2020-04-21 07:59:20 +02:00
#include <CommonCrypto/CommonHMAC.h>
2019-09-10 23:05:07 +02:00
#elif defined(IXCRYPTO_USE_OPEN_SSL)
2020-04-21 07:59:20 +02:00
#include <openssl/hmac.h>
2019-09-10 23:05:07 +02:00
#else
2020-04-21 07:59:20 +02:00
#include <assert.h>
#endif
namespace ix
{
std::string hmac(const std::string& data, const std::string& key)
{
constexpr size_t hashSize = 16;
unsigned char hash[hashSize];
2019-09-10 23:05:07 +02:00
#if defined(IXCRYPTO_USE_MBED_TLS)
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_MD5),
2020-04-21 07:59:20 +02:00
(unsigned char*) key.c_str(),
key.size(),
(unsigned char*) data.c_str(),
data.size(),
(unsigned char*) &hash);
#elif defined(__APPLE__)
2020-04-21 07:59:20 +02:00
CCHmac(kCCHmacAlgMD5, key.c_str(), key.size(), data.c_str(), data.size(), &hash);
2019-09-10 23:05:07 +02:00
#elif defined(IXCRYPTO_USE_OPEN_SSL)
HMAC(EVP_md5(),
2020-04-21 07:59:20 +02:00
key.c_str(),
(int) key.size(),
(unsigned char*) data.c_str(),
(int) data.size(),
(unsigned char*) hash,
nullptr);
2019-09-10 23:05:07 +02:00
#else
assert(false && "hmac not implemented on this platform");
#endif
std::string hashString(reinterpret_cast<char*>(hash), hashSize);
return base64_encode(hashString, (uint32_t) hashString.size());
}
2020-04-21 07:59:20 +02:00
} // namespace ix