sha.c 1.26 KB
Newer Older
1
/*
2
 * Copyright (c) 2015-2017, ARM Limited and Contributors. All rights reserved.
3
 *
dp-arm's avatar
dp-arm committed
4
 * SPDX-License-Identifier: BSD-3-Clause
5
6
7
 */

#include <openssl/sha.h>
Isla Mitchell's avatar
Isla Mitchell committed
8
#include <stdio.h>
9
#include "debug.h"
10
#include "key.h"
11
12
13

#define BUFFER_SIZE	256

14
int sha_file(int md_alg, const char *filename, unsigned char *md)
15
16
17
{
	FILE *inFile;
	SHA256_CTX shaContext;
18
	SHA512_CTX sha512Context;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
	int bytes;
	unsigned char data[BUFFER_SIZE];

	if ((filename == NULL) || (md == NULL)) {
		ERROR("%s(): NULL argument\n", __FUNCTION__);
		return 0;
	}

	inFile = fopen(filename, "rb");
	if (inFile == NULL) {
		ERROR("Cannot read %s\n", filename);
		return 0;
	}

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
	if (md_alg == HASH_ALG_SHA384) {
		SHA384_Init(&sha512Context);
		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
			SHA384_Update(&sha512Context, data, bytes);
		}
		SHA384_Final(md, &sha512Context);
	} else if (md_alg == HASH_ALG_SHA512) {
		SHA512_Init(&sha512Context);
		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
			SHA512_Update(&sha512Context, data, bytes);
		}
		SHA512_Final(md, &sha512Context);
	} else {
		SHA256_Init(&shaContext);
		while ((bytes = fread(data, 1, BUFFER_SIZE, inFile)) != 0) {
			SHA256_Update(&shaContext, data, bytes);
		}
		SHA256_Final(md, &shaContext);
51
52
53
54
55
	}

	fclose(inFile);
	return 1;
}