blob: ef6ad824ba153a5df5e8100d83cc9bdeaf5c1006 [file] [log] [blame]
nagendra modadugu4fae5422016-05-10 16:11:54 -07001// Copyright 2016 Google Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14#include "cryptoc/hmac.h"
15#include "cryptoc/util.h"
16
17#include <string.h>
18#include "cryptoc/sha.h"
19#include "cryptoc/md5.h"
20#include "cryptoc/sha256.h"
21
22static void HMAC_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) {
23 unsigned int i;
24 memset(&ctx->opad[0], 0, sizeof(ctx->opad));
25
26 if (len > sizeof(ctx->opad)) {
27 HASH_init(&ctx->hash);
28 HASH_update(&ctx->hash, key, len);
29 memcpy(&ctx->opad[0], HASH_final(&ctx->hash), HASH_size(&ctx->hash));
30 } else {
31 memcpy(&ctx->opad[0], key, len);
32 }
33
34 for (i = 0; i < sizeof(ctx->opad); ++i) {
35 ctx->opad[i] ^= 0x36;
36 }
37
38 HASH_init(&ctx->hash);
39 HASH_update(&ctx->hash, ctx->opad, sizeof(ctx->opad)); // hash ipad
40
41 for (i = 0; i < sizeof(ctx->opad); ++i) {
42 ctx->opad[i] ^= (0x36 ^ 0x5c);
43 }
44}
45
46void HMAC_MD5_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) {
47 MD5_init(&ctx->hash);
48 HMAC_init(ctx, key, len);
49}
50
51void HMAC_SHA_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) {
52 SHA_init(&ctx->hash);
53 HMAC_init(ctx, key, len);
54}
55
56void HMAC_SHA256_init(LITE_HMAC_CTX* ctx, const void* key, unsigned int len) {
57 SHA256_init(&ctx->hash);
58 HMAC_init(ctx, key, len);
59}
60
61const uint8_t* HMAC_final(LITE_HMAC_CTX* ctx) {
62 uint8_t digest[32]; // upto SHA2
63 memcpy(digest, HASH_final(&ctx->hash),
64 (HASH_size(&ctx->hash) <= sizeof(digest) ?
65 HASH_size(&ctx->hash) : sizeof(digest)));
66 HASH_init(&ctx->hash);
67 HASH_update(&ctx->hash, ctx->opad, sizeof(ctx->opad));
68 HASH_update(&ctx->hash, digest, HASH_size(&ctx->hash));
69 always_memset(&ctx->opad[0], 0, sizeof(ctx->opad)); // wipe key
70 return HASH_final(&ctx->hash);
71}