1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file pmac_file.c
7    PMAC implementation, process a file, by Tom St Denis
8 */
9 
10 #ifdef LTC_PMAC
11 
12 /**
13    PMAC a file
14    @param cipher       The index of the cipher desired
15    @param key          The secret key
16    @param keylen       The length of the secret key (octets)
17    @param filename     The name of the file to send through PMAC
18    @param out          [out] Destination for the authentication tag
19    @param outlen       [in/out] Max size and resulting size of the authentication tag
20    @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
21 */
pmac_file(int cipher,const unsigned char * key,unsigned long keylen,const char * filename,unsigned char * out,unsigned long * outlen)22 int pmac_file(int cipher,
23               const unsigned char *key, unsigned long keylen,
24               const char *filename,
25                     unsigned char *out, unsigned long *outlen)
26 {
27 #ifdef LTC_NO_FILE
28    LTC_UNUSED_PARAM(cipher);
29    LTC_UNUSED_PARAM(key);
30    LTC_UNUSED_PARAM(keylen);
31    LTC_UNUSED_PARAM(filename);
32    LTC_UNUSED_PARAM(out);
33    LTC_UNUSED_PARAM(outlen);
34    return CRYPT_NOP;
35 #else
36    size_t x;
37    int err;
38    pmac_state pmac;
39    FILE *in;
40    unsigned char *buf;
41 
42 
43    LTC_ARGCHK(key      != NULL);
44    LTC_ARGCHK(filename != NULL);
45    LTC_ARGCHK(out      != NULL);
46    LTC_ARGCHK(outlen   != NULL);
47 
48    if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
49       return CRYPT_MEM;
50    }
51 
52    if ((err = pmac_init(&pmac, cipher, key, keylen)) != CRYPT_OK) {
53       goto LBL_ERR;
54    }
55 
56    in = fopen(filename, "rb");
57    if (in == NULL) {
58       err = CRYPT_FILE_NOTFOUND;
59       goto LBL_ERR;
60    }
61 
62    do {
63       x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
64       if ((err = pmac_process(&pmac, buf, (unsigned long)x)) != CRYPT_OK) {
65          fclose(in);
66          goto LBL_CLEANBUF;
67       }
68    } while (x == LTC_FILE_READ_BUFSIZE);
69 
70    if (fclose(in) != 0) {
71       err = CRYPT_ERROR;
72       goto LBL_CLEANBUF;
73    }
74 
75    err = pmac_done(&pmac, out, outlen);
76 
77 LBL_CLEANBUF:
78    zeromem(buf, LTC_FILE_READ_BUFSIZE);
79 LBL_ERR:
80 #ifdef LTC_CLEAN_STACK
81    zeromem(&pmac, sizeof(pmac_state));
82 #endif
83    XFREE(buf);
84    return err;
85 #endif
86 }
87 
88 #endif
89