1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file xcbc_file.c
7   XCBC support, process a file, Tom St Denis
8 */
9 
10 #ifdef LTC_XCBC
11 
12 /**
13    XCBC 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 you wish to XCBC
18    @param out      [out] Where the authentication tag is to be stored
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 */
xcbc_file(int cipher,const unsigned char * key,unsigned long keylen,const char * filename,unsigned char * out,unsigned long * outlen)22 int xcbc_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    xcbc_state xcbc;
39    FILE *in;
40    unsigned char *buf;
41 
42    LTC_ARGCHK(key      != NULL);
43    LTC_ARGCHK(filename != NULL);
44    LTC_ARGCHK(out      != NULL);
45    LTC_ARGCHK(outlen   != NULL);
46 
47    if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
48       return CRYPT_MEM;
49    }
50 
51    if ((err = xcbc_init(&xcbc, cipher, key, keylen)) != CRYPT_OK) {
52       goto LBL_ERR;
53    }
54 
55    in = fopen(filename, "rb");
56    if (in == NULL) {
57       err = CRYPT_FILE_NOTFOUND;
58       goto LBL_ERR;
59    }
60 
61    do {
62       x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
63       if ((err = xcbc_process(&xcbc, buf, (unsigned long)x)) != CRYPT_OK) {
64          fclose(in);
65          goto LBL_CLEANBUF;
66       }
67    } while (x == LTC_FILE_READ_BUFSIZE);
68 
69    if (fclose(in) != 0) {
70       err = CRYPT_ERROR;
71       goto LBL_CLEANBUF;
72    }
73 
74    err = xcbc_done(&xcbc, out, outlen);
75 
76 LBL_CLEANBUF:
77    zeromem(buf, LTC_FILE_READ_BUFSIZE);
78 LBL_ERR:
79 #ifdef LTC_CLEAN_STACK
80    zeromem(&xcbc, sizeof(xcbc_state));
81 #endif
82    XFREE(buf);
83    return err;
84 #endif
85 }
86 
87 #endif
88