OLD | NEW |
| (Empty) |
1 // Copyright 2007-2009 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 // ======================================================================== | |
15 // | |
16 // Optimized for minimal code size. | |
17 | |
18 #include "hmac.h" | |
19 | |
20 #include <memory.h> | |
21 #include "sha.h" | |
22 #include "md5.h" | |
23 | |
24 static void HMAC_init(HMAC_CTX* ctx, const void* key, int len) { | |
25 int i; | |
26 memset(&ctx->opad[0], 0, sizeof(ctx->opad)); | |
27 | |
28 if (len > sizeof(ctx->opad)) { | |
29 HASH_init(&ctx->hash); | |
30 HASH_update(&ctx->hash, key, len); | |
31 memcpy(&ctx->opad[0], HASH_final(&ctx->hash), HASH_size(&ctx->hash)); | |
32 } else { | |
33 memcpy(&ctx->opad[0], key, len); | |
34 } | |
35 | |
36 for (i = 0; i < sizeof(ctx->opad); ++i) { | |
37 ctx->opad[i] ^= 0x36; | |
38 } | |
39 | |
40 HASH_init(&ctx->hash); | |
41 HASH_update(&ctx->hash, ctx->opad, sizeof(ctx->opad)); // hash ipad | |
42 | |
43 for (i = 0; i < sizeof(ctx->opad); ++i) { | |
44 ctx->opad[i] ^= (0x36 ^ 0x5c); | |
45 } | |
46 } | |
47 | |
48 void HMAC_MD5_init(HMAC_CTX* ctx, const void* key, int len) { | |
49 MD5_init(&ctx->hash); | |
50 HMAC_init(ctx, key, len); | |
51 } | |
52 | |
53 void HMAC_SHA_init(HMAC_CTX* ctx, const void* key, int len) { | |
54 SHA_init(&ctx->hash); | |
55 HMAC_init(ctx, key, len); | |
56 } | |
57 | |
58 const uint8_t* HMAC_final(HMAC_CTX* ctx) { | |
59 uint8_t digest[32]; // upto SHA2 | |
60 memcpy(digest, HASH_final(&ctx->hash), | |
61 (HASH_size(&ctx->hash) <= sizeof(digest) ? | |
62 HASH_size(&ctx->hash) : sizeof(digest))); | |
63 HASH_init(&ctx->hash); | |
64 HASH_update(&ctx->hash, ctx->opad, sizeof(ctx->opad)); | |
65 HASH_update(&ctx->hash, digest, HASH_size(&ctx->hash)); | |
66 memset(&ctx->opad[0], 0, sizeof(ctx->opad)); // wipe key | |
67 return HASH_final(&ctx->hash); | |
68 } | |
OLD | NEW |