1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 
4 #include "tomcrypt_private.h"
5 
6 #ifdef LTC_BLAKE2BMAC
7 
8 /**
9   BLAKE2B MAC a file
10   @param fname    The name of the file you wish to BLAKE2B MAC
11   @param key      The secret key
12   @param keylen   The length of the secret key
13   @param mac      [out] The BLAKE2B MAC authentication tag
14   @param maclen   [in/out]  The max size and resulting size of the authentication tag
15   @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
16 */
blake2bmac_file(const char * fname,const unsigned char * key,unsigned long keylen,unsigned char * mac,unsigned long * maclen)17 int blake2bmac_file(const char *fname, const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen)
18 {
19 #ifdef LTC_NO_FILE
20    LTC_UNUSED_PARAM(fname);
21    LTC_UNUSED_PARAM(key);
22    LTC_UNUSED_PARAM(keylen);
23    LTC_UNUSED_PARAM(mac);
24    LTC_UNUSED_PARAM(maclen);
25    return CRYPT_NOP;
26 #else
27    blake2bmac_state st;
28    FILE *in;
29    unsigned char *buf;
30    size_t x;
31    int err;
32 
33    LTC_ARGCHK(fname  != NULL);
34    LTC_ARGCHK(key    != NULL);
35    LTC_ARGCHK(mac    != NULL);
36    LTC_ARGCHK(maclen != NULL);
37 
38    if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
39       return CRYPT_MEM;
40    }
41 
42    if ((err = blake2bmac_init(&st, *maclen, key, keylen)) != CRYPT_OK) {
43       goto LBL_ERR;
44    }
45 
46    in = fopen(fname, "rb");
47    if (in == NULL) {
48       err = CRYPT_FILE_NOTFOUND;
49       goto LBL_ERR;
50    }
51 
52    do {
53       x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
54       if ((err = blake2bmac_process(&st, buf, (unsigned long)x)) != CRYPT_OK) {
55          fclose(in);
56          goto LBL_CLEANBUF;
57       }
58    } while (x == LTC_FILE_READ_BUFSIZE);
59 
60    if (fclose(in) != 0) {
61       err = CRYPT_ERROR;
62       goto LBL_CLEANBUF;
63    }
64 
65    err = blake2bmac_done(&st, mac, maclen);
66 
67 LBL_CLEANBUF:
68    zeromem(buf, LTC_FILE_READ_BUFSIZE);
69 LBL_ERR:
70 #ifdef LTC_CLEAN_STACK
71    zeromem(&st, sizeof(blake2bmac_state));
72 #endif
73    XFREE(buf);
74    return err;
75 #endif
76 }
77 
78 #endif
79