1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10 #include "tomcrypt_private.h"
11
12 /**
13 @file hmac_memory.c
14 HMAC support, process a block of memory, Tom St Denis/Dobes Vandermeer
15 */
16
17 #ifdef LTC_HMAC
18
19 /**
20 HMAC a block of memory to produce the authentication tag
21 @param hash The index of the hash to use
22 @param key The secret key
23 @param keylen The length of the secret key (octets)
24 @param in The data to HMAC
25 @param inlen The length of the data to HMAC (octets)
26 @param out [out] Destination of the authentication tag
27 @param outlen [in/out] Max size and resulting size of authentication tag
28 @return CRYPT_OK if successful
29 */
hmac_memory(int hash,const unsigned char * key,unsigned long keylen,const unsigned char * in,unsigned long inlen,unsigned char * out,unsigned long * outlen)30 int hmac_memory(int hash,
31 const unsigned char *key, unsigned long keylen,
32 const unsigned char *in, unsigned long inlen,
33 unsigned char *out, unsigned long *outlen)
34 {
35 hmac_state *hmac;
36 int err;
37
38 LTC_ARGCHK(key != NULL);
39 LTC_ARGCHK(in != NULL);
40 LTC_ARGCHK(out != NULL);
41 LTC_ARGCHK(outlen != NULL);
42
43 /* make sure hash descriptor is valid */
44 if ((err = hash_is_valid(hash)) != CRYPT_OK) {
45 return err;
46 }
47
48 /* is there a descriptor? */
49 if (hash_descriptor[hash]->hmac_block != NULL) {
50 return hash_descriptor[hash]->hmac_block(key, keylen, in, inlen, out, outlen);
51 }
52
53 /* nope, so call the hmac functions */
54 /* allocate ram for hmac state */
55 hmac = XMALLOC(sizeof(hmac_state));
56 if (hmac == NULL) {
57 return CRYPT_MEM;
58 }
59
60 if ((err = hmac_init(hmac, hash, key, keylen)) != CRYPT_OK) {
61 goto LBL_ERR;
62 }
63
64 if ((err = hmac_process(hmac, in, inlen)) != CRYPT_OK) {
65 goto LBL_ERR;
66 }
67
68 if ((err = hmac_done(hmac, out, outlen)) != CRYPT_OK) {
69 goto LBL_ERR;
70 }
71
72 err = CRYPT_OK;
73 LBL_ERR:
74 #ifdef LTC_CLEAN_STACK
75 zeromem(hmac, sizeof(hmac_state));
76 #endif
77
78 XFREE(hmac);
79 return err;
80 }
81
82 #endif
83
84
85 /* ref: $Format:%D$ */
86 /* git commit: $Format:%H$ */
87 /* commit time: $Format:%ai$ */
88