1 /*
2  * Copyright (c) 2015-2017, ARM Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <openssl/sha.h>
8 #include <stdio.h>
9 #include "debug.h"
10 #include "key.h"
11 
12 #define BUFFER_SIZE	256
13 
sha_file(int md_alg,const char * filename,unsigned char * md)14 int sha_file(int md_alg, const char *filename, unsigned char *md)
15 {
16 	FILE *inFile;
17 	SHA256_CTX shaContext;
18 	SHA512_CTX sha512Context;
19 	int bytes;
20 	unsigned char data[BUFFER_SIZE];
21 
22 	if ((filename == NULL) || (md == NULL)) {
23 		ERROR("%s(): NULL argument\n", __FUNCTION__);
24 		return 0;
25 	}
26 
27 	inFile = fopen(filename, "rb");
28 	if (inFile == NULL) {
29 		ERROR("Cannot read %s\n", filename);
30 		return 0;
31 	}
32 
33 	if (md_alg == HASH_ALG_SHA384) {
34 		SHA384_Init(&sha512Context);
35 		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
36 			SHA384_Update(&sha512Context, data, bytes);
37 		}
38 		SHA384_Final(md, &sha512Context);
39 	} else if (md_alg == HASH_ALG_SHA512) {
40 		SHA512_Init(&sha512Context);
41 		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
42 			SHA512_Update(&sha512Context, data, bytes);
43 		}
44 		SHA512_Final(md, &sha512Context);
45 	} else {
46 		SHA256_Init(&shaContext);
47 		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
48 			SHA256_Update(&shaContext, data, bytes);
49 		}
50 		SHA256_Final(md, &shaContext);
51 	}
52 
53 	fclose(inFile);
54 	return 1;
55 }
56