1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 #ifdef LTC_HASH_HELPERS
6 /**
7   @file hash_memory.c
8   Hash memory helper, Tom St Denis
9 */
10 
11 /**
12   Hash a block of memory and store the digest.
13   @param hash   The index of the hash you wish to use
14   @param in     The data you wish to hash
15   @param inlen  The length of the data to hash (octets)
16   @param out    [out] Where to store the digest
17   @param outlen [in/out] Max size and resulting size of the digest
18   @return CRYPT_OK if successful
19 */
hash_memory(int hash,const unsigned char * in,unsigned long inlen,unsigned char * out,unsigned long * outlen)20 int hash_memory(int hash, const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen)
21 {
22     hash_state *md;
23     int err;
24 
25     LTC_ARGCHK(in     != NULL);
26     LTC_ARGCHK(out    != NULL);
27     LTC_ARGCHK(outlen != NULL);
28 
29     if ((err = hash_is_valid(hash)) != CRYPT_OK) {
30         return err;
31     }
32 
33     if (*outlen < hash_descriptor[hash]->hashsize) {
34        *outlen = hash_descriptor[hash]->hashsize;
35        return CRYPT_BUFFER_OVERFLOW;
36     }
37 
38     md = XMALLOC(sizeof(hash_state));
39     if (md == NULL) {
40        return CRYPT_MEM;
41     }
42 
43     if ((err = hash_descriptor[hash]->init(md)) != CRYPT_OK) {
44        goto LBL_ERR;
45     }
46     if ((err = hash_descriptor[hash]->process(md, in, inlen)) != CRYPT_OK) {
47        goto LBL_ERR;
48     }
49     err = hash_descriptor[hash]->done(md, out);
50     *outlen = hash_descriptor[hash]->hashsize;
51 LBL_ERR:
52 #ifdef LTC_CLEAN_STACK
53     zeromem(md, sizeof(hash_state));
54 #endif
55     XFREE(md);
56 
57     return err;
58 }
59 #endif /* #ifdef LTC_HASH_HELPERS */
60