1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6   @file f9_file.c
7   f9 support, process a file, Tom St Denis
8 */
9 
10 #ifdef LTC_F9_MODE
11 
12 /**
13    f9 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 fname    The name of the file you wish to f9
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 */
f9_file(int cipher,const unsigned char * key,unsigned long keylen,const char * fname,unsigned char * out,unsigned long * outlen)22 int f9_file(int cipher,
23               const unsigned char *key, unsigned long keylen,
24               const char *fname,
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(fname);
32    LTC_UNUSED_PARAM(out);
33    LTC_UNUSED_PARAM(outlen);
34    return CRYPT_NOP;
35 #else
36    size_t x;
37    int err;
38    f9_state f9;
39    FILE *in;
40    unsigned char *buf;
41 
42    LTC_ARGCHK(key    != NULL);
43    LTC_ARGCHK(fname  != 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 = f9_init(&f9, cipher, key, keylen)) != CRYPT_OK) {
52       goto LBL_ERR;
53    }
54 
55    in = fopen(fname, "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 = f9_process(&f9, 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 = f9_done(&f9, out, outlen);
75 
76 LBL_CLEANBUF:
77    zeromem(buf, LTC_FILE_READ_BUFSIZE);
78 LBL_ERR:
79 #ifdef LTC_CLEAN_STACK
80    zeromem(&f9, sizeof(f9_state));
81 #endif
82    XFREE(buf);
83    return err;
84 #endif
85 }
86 
87 #endif
88