Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 1 | /* |
Qixiang Xu | 76a5a9b | 2017-11-09 13:51:58 +0800 | [diff] [blame] | 2 | * Copyright (c) 2015-2017, ARM Limited and Contributors. All rights reserved. |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 3 | * |
dp-arm | fa3cf0b | 2017-05-03 09:38:09 +0100 | [diff] [blame] | 4 | * SPDX-License-Identifier: BSD-3-Clause |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 5 | */ |
| 6 | |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 7 | #include <openssl/sha.h> |
Isla Mitchell | 9930501 | 2017-07-11 14:54:08 +0100 | [diff] [blame] | 8 | #include <stdio.h> |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 9 | #include "debug.h" |
Qixiang Xu | 76a5a9b | 2017-11-09 13:51:58 +0800 | [diff] [blame] | 10 | #include "key.h" |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 11 | |
| 12 | #define BUFFER_SIZE 256 |
| 13 | |
Qixiang Xu | 76a5a9b | 2017-11-09 13:51:58 +0800 | [diff] [blame] | 14 | int sha_file(int md_alg, const char *filename, unsigned char *md) |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 15 | { |
| 16 | FILE *inFile; |
| 17 | SHA256_CTX shaContext; |
Qixiang Xu | 76a5a9b | 2017-11-09 13:51:58 +0800 | [diff] [blame] | 18 | SHA512_CTX sha512Context; |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 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 | |
Qixiang Xu | 76a5a9b | 2017-11-09 13:51:58 +0800 | [diff] [blame] | 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); |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 51 | } |
Juan Castillo | 11abdcd | 2014-10-21 11:30:42 +0100 | [diff] [blame] | 52 | |
| 53 | fclose(inFile); |
| 54 | return 1; |
| 55 | } |