1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10 #include "tomcrypt_private.h"
11
12 #ifndef LTC_NO_FILE
13 /**
14 @file hash_filehandle.c
15 Hash open files, Tom St Denis
16 */
17
18 /**
19 Hash data from an open file handle.
20 @param hash The index of the hash you want to use
21 @param in The FILE* handle of the file you want to hash
22 @param out [out] The destination of the digest
23 @param outlen [in/out] The max size and resulting size of the digest
24 @result CRYPT_OK if successful
25 */
hash_filehandle(int hash,FILE * in,unsigned char * out,unsigned long * outlen)26 int hash_filehandle(int hash, FILE *in, unsigned char *out, unsigned long *outlen)
27 {
28 hash_state md;
29 unsigned char *buf;
30 size_t x;
31 int err;
32
33 LTC_ARGCHK(out != NULL);
34 LTC_ARGCHK(outlen != NULL);
35 LTC_ARGCHK(in != NULL);
36
37 if ((buf = XMALLOC(LTC_FILE_READ_BUFSIZE)) == NULL) {
38 return CRYPT_MEM;
39 }
40
41 if ((err = hash_is_valid(hash)) != CRYPT_OK) {
42 goto LBL_ERR;
43 }
44
45 if (*outlen < hash_descriptor[hash]->hashsize) {
46 *outlen = hash_descriptor[hash]->hashsize;
47 err = CRYPT_BUFFER_OVERFLOW;
48 goto LBL_ERR;
49 }
50 if ((err = hash_descriptor[hash]->init(&md)) != CRYPT_OK) {
51 goto LBL_ERR;
52 }
53
54 do {
55 x = fread(buf, 1, LTC_FILE_READ_BUFSIZE, in);
56 if ((err = hash_descriptor[hash]->process(&md, buf, (unsigned long)x)) != CRYPT_OK) {
57 goto LBL_CLEANBUF;
58 }
59 } while (x == LTC_FILE_READ_BUFSIZE);
60 if ((err = hash_descriptor[hash]->done(&md, out)) == CRYPT_OK) {
61 *outlen = hash_descriptor[hash]->hashsize;
62 }
63
64 LBL_CLEANBUF:
65 zeromem(buf, LTC_FILE_READ_BUFSIZE);
66 LBL_ERR:
67 XFREE(buf);
68 return err;
69 }
70 #endif /* #ifndef LTC_NO_FILE */
71
72
73 /* ref: $Format:%D$ */
74 /* git commit: $Format:%H$ */
75 /* commit time: $Format:%ai$ */
76