hmac: add sha256 support

This commit is contained in:
Richard Aas 2016-02-01 08:04:53 +00:00
parent a9a987942d
commit bfa2112207
3 changed files with 34 additions and 7 deletions

View file

@ -14,7 +14,8 @@ void hmac_sha1(const uint8_t *k, /* secret key */
enum hmac_hash {
HMAC_HASH_SHA1
HMAC_HASH_SHA1,
HMAC_HASH_SHA256
};
struct hmac;

View file

@ -12,12 +12,13 @@
#include <re_hmac.h>
enum { KEY_SIZE = 20 };
enum { KEY_SIZE = 256 };
struct hmac {
CCHmacContext ctx;
uint8_t key[KEY_SIZE];
size_t key_len;
CCHmacAlgorithm algo;
};
@ -33,12 +34,24 @@ int hmac_create(struct hmac **hmacp, enum hmac_hash hash,
const uint8_t *key, size_t key_len)
{
struct hmac *hmac;
CCHmacAlgorithm algo;
if (!hmacp || !key || !key_len || key_len > KEY_SIZE)
return EINVAL;
if (hash != HMAC_HASH_SHA1)
switch (hash) {
case HMAC_HASH_SHA1:
algo = kCCHmacAlgSHA1;
break;
case HMAC_HASH_SHA256:
algo = kCCHmacAlgSHA256;
break;
default:
return ENOTSUP;
}
hmac = mem_zalloc(sizeof(*hmac), destructor);
if (!hmac)
@ -46,6 +59,7 @@ int hmac_create(struct hmac **hmacp, enum hmac_hash hash,
memcpy(hmac->key, key, key_len);
hmac->key_len = key_len;
hmac->algo = algo;
*hmacp = hmac;
@ -60,7 +74,7 @@ int hmac_digest(struct hmac *hmac, uint8_t *md, size_t md_len,
return EINVAL;
/* reset state */
CCHmacInit(&hmac->ctx, kCCHmacAlgSHA1, hmac->key, hmac->key_len);
CCHmacInit(&hmac->ctx, hmac->algo, hmac->key, hmac->key_len);
CCHmacUpdate(&hmac->ctx, data, data_len);
CCHmacFinal(&hmac->ctx, md);

View file

@ -28,13 +28,25 @@ int hmac_create(struct hmac **hmacp, enum hmac_hash hash,
const uint8_t *key, size_t key_len)
{
struct hmac *hmac;
const EVP_MD *evp;
int err = 0;
if (!hmacp || !key || !key_len)
return EINVAL;
if (hash != HMAC_HASH_SHA1)
switch (hash) {
case HMAC_HASH_SHA1:
evp = EVP_sha1();
break;
case HMAC_HASH_SHA256:
evp = EVP_sha256();
break;
default:
return ENOTSUP;
}
hmac = mem_zalloc(sizeof(*hmac), destructor);
if (!hmac)
@ -43,12 +55,12 @@ int hmac_create(struct hmac **hmacp, enum hmac_hash hash,
HMAC_CTX_init(&hmac->ctx);
#if (OPENSSL_VERSION_NUMBER >= 0x00909000)
if (!HMAC_Init_ex(&hmac->ctx, key, (int)key_len, EVP_sha1(), NULL)) {
if (!HMAC_Init_ex(&hmac->ctx, key, (int)key_len, evp, NULL)) {
ERR_clear_error();
err = EPROTO;
}
#else
HMAC_Init_ex(&hmac->ctx, key, (int)key_len, EVP_sha1(), NULL);
HMAC_Init_ex(&hmac->ctx, key, (int)key_len, evp, NULL);
#endif
if (err)