diff --git a/include/re_hmac.h b/include/re_hmac.h index 9660d04..25e7e2e 100644 --- a/include/re_hmac.h +++ b/include/re_hmac.h @@ -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; diff --git a/src/hmac/apple/hmac.c b/src/hmac/apple/hmac.c index fb38f69..34099d6 100644 --- a/src/hmac/apple/hmac.c +++ b/src/hmac/apple/hmac.c @@ -12,12 +12,13 @@ #include -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); diff --git a/src/hmac/openssl/hmac.c b/src/hmac/openssl/hmac.c index 1701a8c..4813f86 100644 --- a/src/hmac/openssl/hmac.c +++ b/src/hmac/openssl/hmac.c @@ -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)