1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /**
6 @file hmac_file.c
7 HMAC support, process a file, Tom St Denis/Dobes Vandermeer
8 */
9
10 #ifdef LTC_HMAC
11
12 /**
13 HMAC a file
14 @param hash The index of the hash you wish to use
15 @param fname The name of the file you wish to HMAC
16 @param key The secret key
17 @param keylen The length of the secret key
18 @param out [out] The HMAC authentication tag
19 @param outlen [in/out] The max size and resulting size of the authentication tag
20 @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
21 */
hmac_file(int hash,const char * fname,const unsigned char * key,unsigned long keylen,unsigned char * out,unsigned long * outlen)22 int hmac_file(int hash, const char *fname,
23 const unsigned char *key, unsigned long keylen,
24 unsigned char *out, unsigned long *outlen)
25 {
26 #ifdef LTC_NO_FILE
27 LTC_UNUSED_PARAM(hash);
28 LTC_UNUSED_PARAM(fname);
29 LTC_UNUSED_PARAM(key);
30 LTC_UNUSED_PARAM(keylen);
31 LTC_UNUSED_PARAM(out);
32 LTC_UNUSED_PARAM(outlen);
33 return CRYPT_NOP;
34 #else
35 hmac_state hmac;
36 FILE *in;
37 unsigned char *buf;
38 size_t x;
39 int err;
40
41 LTC_ARGCHK(fname != NULL);
42 LTC_ARGCHK(key != NULL);
43 LTC_ARGCHK(out != NULL);
44 LTC_ARGCHK(outlen != NULL);
45
46 if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
47 return CRYPT_MEM;
48 }
49
50 if ((err = hash_is_valid(hash)) != CRYPT_OK) {
51 goto LBL_ERR;
52 }
53
54 if ((err = hmac_init(&hmac, hash, key, keylen)) != CRYPT_OK) {
55 goto LBL_ERR;
56 }
57
58 in = fopen(fname, "rb");
59 if (in == NULL) {
60 err = CRYPT_FILE_NOTFOUND;
61 goto LBL_ERR;
62 }
63
64 do {
65 x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
66 if ((err = hmac_process(&hmac, buf, (unsigned long)x)) != CRYPT_OK) {
67 fclose(in); /* we don't trap this error since we're already returning an error! */
68 goto LBL_CLEANBUF;
69 }
70 } while (x == LTC_FILE_READ_BUFSIZE);
71
72 if (fclose(in) != 0) {
73 err = CRYPT_ERROR;
74 goto LBL_CLEANBUF;
75 }
76
77 err = hmac_done(&hmac, out, outlen);
78
79 LBL_CLEANBUF:
80 zeromem(buf, LTC_FILE_READ_BUFSIZE);
81 LBL_ERR:
82 #ifdef LTC_CLEAN_STACK
83 zeromem(&hmac, sizeof(hmac_state));
84 #endif
85 XFREE(buf);
86 return err;
87 #endif
88 }
89
90 #endif
91