]> pd.if.org Git - zpackage/blob - libtomcrypt/src/mac/poly1305/poly1305_file.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / mac / poly1305 / poly1305_file.c
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2  *
3  * LibTomCrypt is a library that provides various cryptographic
4  * algorithms in a highly modular and flexible manner.
5  *
6  * The library is free for all purposes without any express
7  * guarantee it works.
8  */
9
10 /* The implementation is based on:
11  * Public Domain poly1305 from Andrew Moon
12  * https://github.com/floodyberry/poly1305-donna
13  */
14
15 #include "tomcrypt.h"
16
17 #ifdef LTC_POLY1305
18
19 /**
20   POLY1305 a file
21   @param fname    The name of the file you wish to POLY1305
22   @param key      The secret key
23   @param keylen   The length of the secret key
24   @param mac      [out] The POLY1305 authentication tag
25   @param maclen   [in/out]  The max size and resulting size of the authentication tag
26   @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
27 */
28 int poly1305_file(const char *fname, const unsigned char *key, unsigned long keylen, unsigned char *mac, unsigned long *maclen)
29 {
30 #ifdef LTC_NO_FILE
31    LTC_UNUSED_PARAM(fname);
32    LTC_UNUSED_PARAM(key);
33    LTC_UNUSED_PARAM(keylen);
34    LTC_UNUSED_PARAM(mac);
35    LTC_UNUSED_PARAM(maclen);
36    return CRYPT_NOP;
37 #else
38    poly1305_state st;
39    FILE *in;
40    unsigned char *buf;
41    size_t x;
42    int err;
43
44    LTC_ARGCHK(fname  != NULL);
45    LTC_ARGCHK(key    != NULL);
46    LTC_ARGCHK(mac    != NULL);
47    LTC_ARGCHK(maclen != NULL);
48
49    if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
50       return CRYPT_MEM;
51    }
52
53    if ((err = poly1305_init(&st, key, keylen)) != CRYPT_OK) {
54       goto LBL_ERR;
55    }
56
57    in = fopen(fname, "rb");
58    if (in == NULL) {
59       err = CRYPT_FILE_NOTFOUND;
60       goto LBL_ERR;
61    }
62
63    do {
64       x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
65       if ((err = poly1305_process(&st, buf, (unsigned long)x)) != CRYPT_OK) {
66          fclose(in);
67          goto LBL_CLEANBUF;
68       }
69    } while (x == LTC_FILE_READ_BUFSIZE);
70
71    if (fclose(in) != 0) {
72       err = CRYPT_ERROR;
73       goto LBL_CLEANBUF;
74    }
75
76    err = poly1305_done(&st, mac, maclen);
77
78 LBL_CLEANBUF:
79    zeromem(buf, LTC_FILE_READ_BUFSIZE);
80 LBL_ERR:
81 #ifdef LTC_CLEAN_STACK
82    zeromem(&st, sizeof(poly1305_state));
83 #endif
84    XFREE(buf);
85    return err;
86 #endif
87 }
88
89 #endif
90
91 /* ref:         $Format:%D$ */
92 /* git commit:  $Format:%H$ */
93 /* commit time: $Format:%ai$ */