• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
10  */
11 #include "tomcrypt.h"
12 
13 /**
14   @file hmac_file.c
15   HMAC support, process a file, Tom St Denis/Dobes Vandermeer
16 */
17 
18 #ifdef LTC_HMAC
19 
20 /**
21   HMAC a file
22   @param hash     The index of the hash you wish to use
23   @param fname    The name of the file you wish to HMAC
24   @param key      The secret key
25   @param keylen   The length of the secret key
26   @param out      [out] The HMAC authentication tag
27   @param outlen   [in/out]  The max size and resulting size of the authentication tag
28   @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
29 */
hmac_file(int hash,const char * fname,const unsigned char * key,unsigned long keylen,unsigned char * out,unsigned long * outlen)30 int hmac_file(int hash, const char *fname,
31               const unsigned char *key, unsigned long keylen,
32                     unsigned char *out, unsigned long *outlen)
33 {
34 #ifdef LTC_NO_FILE
35     return CRYPT_NOP;
36 #else
37    hmac_state hmac;
38    FILE *in;
39    unsigned char buf[512];
40    size_t x;
41    int err;
42 
43    LTC_ARGCHK(fname  != NULL);
44    LTC_ARGCHK(key    != NULL);
45    LTC_ARGCHK(out    != NULL);
46    LTC_ARGCHK(outlen != NULL);
47 
48    if((err = hash_is_valid(hash)) != CRYPT_OK) {
49        return err;
50    }
51 
52    if ((err = hmac_init(&hmac, hash, key, keylen)) != CRYPT_OK) {
53        return err;
54    }
55 
56    in = fopen(fname, "rb");
57    if (in == NULL) {
58       return CRYPT_FILE_NOTFOUND;
59    }
60 
61    /* process the file contents */
62    do {
63       x = fread(buf, 1, sizeof(buf), in);
64       if ((err = hmac_process(&hmac, buf, (unsigned long)x)) != CRYPT_OK) {
65          /* we don't trap this error since we're already returning an error! */
66          fclose(in);
67          return err;
68       }
69    } while (x == sizeof(buf));
70 
71    if (fclose(in) != 0) {
72       return CRYPT_ERROR;
73    }
74 
75    /* get final hmac */
76    if ((err = hmac_done(&hmac, out, outlen)) != CRYPT_OK) {
77       return err;
78    }
79 
80 #ifdef LTC_CLEAN_STACK
81    /* clear memory */
82    zeromem(buf, sizeof(buf));
83 #endif
84    return CRYPT_OK;
85 #endif
86 }
87 
88 #endif
89 
90 
91 /* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_file.c,v $ */
92 /* $Revision: 1.5 $ */
93 /* $Date: 2006/11/03 00:39:49 $ */
94