blob: 3d977fbfed7cb80e38a8d65381a549e35e6780d8 [file] [log] [blame]
Juan Castillo11abdcd2014-10-21 11:30:42 +01001/*
Qixiang Xu76a5a9b2017-11-09 13:51:58 +08002 * Copyright (c) 2015-2017, ARM Limited and Contributors. All rights reserved.
Juan Castillo11abdcd2014-10-21 11:30:42 +01003 *
dp-armfa3cf0b2017-05-03 09:38:09 +01004 * SPDX-License-Identifier: BSD-3-Clause
Juan Castillo11abdcd2014-10-21 11:30:42 +01005 */
6
Juan Castillo11abdcd2014-10-21 11:30:42 +01007#include <openssl/sha.h>
Isla Mitchell99305012017-07-11 14:54:08 +01008#include <stdio.h>
Juan Castillo11abdcd2014-10-21 11:30:42 +01009#include "debug.h"
Qixiang Xu76a5a9b2017-11-09 13:51:58 +080010#include "key.h"
Juan Castillo11abdcd2014-10-21 11:30:42 +010011
12#define BUFFER_SIZE 256
13
Qixiang Xu76a5a9b2017-11-09 13:51:58 +080014int sha_file(int md_alg, const char *filename, unsigned char *md)
Juan Castillo11abdcd2014-10-21 11:30:42 +010015{
16 FILE *inFile;
17 SHA256_CTX shaContext;
Qixiang Xu76a5a9b2017-11-09 13:51:58 +080018 SHA512_CTX sha512Context;
Juan Castillo11abdcd2014-10-21 11:30:42 +010019 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
Qixiang Xu76a5a9b2017-11-09 13:51:58 +080033 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);
Juan Castillo11abdcd2014-10-21 11:30:42 +010051 }
Juan Castillo11abdcd2014-10-21 11:30:42 +010052
53 fclose(inFile);
54 return 1;
55}