Vitaly Buka | 47fe6f8 | 2015-12-01 14:37:24 -0800 | [diff] [blame] | 1 | // Copyright 2015 The Weave Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "src/crypto_hmac.h" |
| 6 | |
| 7 | #include <stddef.h> |
| 8 | #include <stdint.h> |
| 9 | #include <string.h> |
| 10 | |
| 11 | #include <openssl/evp.h> |
| 12 | #include <openssl/hmac.h> |
| 13 | |
| 14 | size_t uw_crypto_hmac_required_buffer_size_() { |
| 15 | return sizeof(HMAC_CTX); |
| 16 | } |
| 17 | |
| 18 | bool uw_crypto_hmac_init_(uint8_t* state_buffer, |
| 19 | size_t state_buffer_len, |
| 20 | const uint8_t* key, |
| 21 | size_t key_len) { |
| 22 | if (sizeof(HMAC_CTX) > state_buffer_len) { |
| 23 | return false; |
| 24 | } |
| 25 | HMAC_CTX* context = (HMAC_CTX*)state_buffer; |
| 26 | HMAC_CTX_init(context); |
Vitaly Buka | 1396480 | 2015-12-09 14:18:52 -0800 | [diff] [blame] | 27 | return HMAC_Init(context, key, key_len, EVP_sha256()); |
Vitaly Buka | 47fe6f8 | 2015-12-01 14:37:24 -0800 | [diff] [blame] | 28 | } |
| 29 | |
| 30 | bool uw_crypto_hmac_update_(uint8_t* state_buffer, |
| 31 | size_t state_buffer_len, |
| 32 | const uint8_t* data, |
| 33 | size_t data_len) { |
| 34 | if (sizeof(HMAC_CTX) > state_buffer_len) { |
| 35 | return false; |
| 36 | } |
| 37 | HMAC_CTX* context = (HMAC_CTX*)state_buffer; |
| 38 | return HMAC_Update(context, data, data_len); |
| 39 | } |
| 40 | |
| 41 | bool uw_crypto_hmac_final_(uint8_t* state_buffer, |
| 42 | size_t state_buffer_len, |
| 43 | uint8_t* truncated_digest, |
| 44 | size_t truncated_digest_len) { |
| 45 | if (sizeof(HMAC_CTX) > state_buffer_len) { |
| 46 | return false; |
| 47 | } |
| 48 | HMAC_CTX* context = (HMAC_CTX*)state_buffer; |
| 49 | |
| 50 | const size_t kFullDigestLen = (size_t)EVP_MD_size(EVP_sha256()); |
| 51 | if (truncated_digest_len > kFullDigestLen) { |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | uint8_t digest[kFullDigestLen]; |
| 56 | uint32_t len = kFullDigestLen; |
| 57 | |
| 58 | bool result = HMAC_Final(context, digest, &len) && kFullDigestLen == len; |
| 59 | HMAC_CTX_cleanup(context); |
| 60 | if (result) { |
| 61 | memcpy(truncated_digest, digest, truncated_digest_len); |
| 62 | } |
| 63 | return result; |
| 64 | } |