util: strhex_to_str() fixed to handle '0x' correctly
[Samba/ekacnet.git] / lib / crypto / hmacsha256.c
blob53d4fe388396417dddba4aa56085dc7afaab93da
1 /*
2 Unix SMB/CIFS implementation.
4 Interface header: HMAC SHA-256 code
6 Copyright (C) Andrew Tridgell 2008
8 based in hmacsha1.c which is:
9 Copyright (C) Stefan Metzmacher
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 taken direct from rfc2202 implementation and modified for suitable use
29 #include "includes.h"
30 #include "../lib/crypto/crypto.h"
32 /***********************************************************************
33 the rfc 2104/2202 version of hmac_sha256 initialisation.
34 ***********************************************************************/
35 _PUBLIC_ void hmac_sha256_init(const uint8_t *key, size_t key_len, struct HMACSHA256Context *ctx)
37 int i;
38 uint8_t tk[SHA256_DIGEST_LENGTH];
40 /* if key is longer than 64 bytes reset it to key=HASH(key) */
41 if (key_len > 64)
43 SHA256_CTX tctx;
45 SHA256_Init(&tctx);
46 SHA256_Update(&tctx, key, key_len);
47 SHA256_Final(tk, &tctx);
49 key = tk;
50 key_len = SHA256_DIGEST_LENGTH;
53 /* start out by storing key in pads */
54 ZERO_STRUCT(ctx->k_ipad);
55 ZERO_STRUCT(ctx->k_opad);
56 memcpy( ctx->k_ipad, key, key_len);
57 memcpy( ctx->k_opad, key, key_len);
59 /* XOR key with ipad and opad values */
60 for (i=0; i<64; i++)
62 ctx->k_ipad[i] ^= 0x36;
63 ctx->k_opad[i] ^= 0x5c;
66 SHA256_Init(&ctx->ctx);
67 SHA256_Update(&ctx->ctx, ctx->k_ipad, 64);
70 /***********************************************************************
71 update hmac_sha256 "inner" buffer
72 ***********************************************************************/
73 _PUBLIC_ void hmac_sha256_update(const uint8_t *data, size_t data_len, struct HMACSHA256Context *ctx)
75 SHA256_Update(&ctx->ctx, data, data_len); /* then text of datagram */
78 /***********************************************************************
79 finish off hmac_sha256 "inner" buffer and generate outer one.
80 ***********************************************************************/
81 _PUBLIC_ void hmac_sha256_final(uint8_t digest[SHA256_DIGEST_LENGTH], struct HMACSHA256Context *ctx)
83 SHA256_CTX ctx_o;
85 SHA256_Final(digest, &ctx->ctx);
87 SHA256_Init(&ctx_o);
88 SHA256_Update(&ctx_o, ctx->k_opad, 64);
89 SHA256_Update(&ctx_o, digest, SHA256_DIGEST_LENGTH);
90 SHA256_Final(digest, &ctx_o);