Daisuke Nojiri | e1741c5 | 2015-02-09 18:15:17 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2015 Broadcom Corporation |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or |
| 5 | * modify it under the terms of the GNU General Public License as |
| 6 | * published by the Free Software Foundation version 2. |
| 7 | * |
| 8 | * This program is distributed "as is" WITHOUT ANY WARRANTY of any |
| 9 | * kind, whether express or implied; without even the implied warranty |
| 10 | * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | */ |
| 13 | |
| 14 | |
| 15 | #include <stdio.h> |
| 16 | #include <string.h> |
| 17 | #include <stdint.h> |
| 18 | #include "secimage.h" |
| 19 | #include <openssl/hmac.h> |
| 20 | |
| 21 | |
| 22 | /*---------------------------------------------------------------------- |
| 23 | * Name : HmacSha256Hash |
| 24 | * Purpose : |
| 25 | * Input : none |
| 26 | * Output : none |
| 27 | *---------------------------------------------------------------------*/ |
| 28 | int HmacSha256Hash(uint8_t *data, uint32_t len, uint8_t *hash, uint8_t *key) |
| 29 | { |
| 30 | HMAC_CTX hctx; |
| 31 | |
| 32 | HMAC_CTX_init(&hctx); |
| 33 | HMAC_Init_ex(&hctx, key, 32, EVP_sha256(), NULL); |
| 34 | |
| 35 | /* |
| 36 | * FIXME: why we need this? NULL means to use whatever there is? |
| 37 | * if removed, result is different |
| 38 | */ |
| 39 | HMAC_Init_ex(&hctx, NULL, 0, NULL, NULL); |
| 40 | HMAC_Update(&hctx, data, len); |
| 41 | HMAC_Final(&hctx, hash, NULL); |
| 42 | |
| 43 | HMAC_CTX_cleanup(&hctx); |
| 44 | return 0; |
| 45 | } |
| 46 | |
| 47 | |
| 48 | /*---------------------------------------------------------------------- |
| 49 | * Name : AppendHMACSignature |
| 50 | * Purpose : Appends HMAC signature at the end of the data |
| 51 | *---------------------------------------------------------------------*/ |
| 52 | int AppendHMACSignature(uint8_t *data, uint32_t length, char *filename, |
| 53 | uint32_t offset) |
| 54 | { |
| 55 | uint8_t hmackey[32]; |
| 56 | uint32_t len; |
| 57 | uint32_t status; |
| 58 | uint8_t *digest = data + length; |
| 59 | |
| 60 | len = ReadBinaryFile(filename, hmackey, 32); |
| 61 | if (len != 32) { |
| 62 | printf("Error reading hmac key file\n"); |
| 63 | return 0; |
| 64 | } |
| 65 | |
| 66 | status = HmacSha256Hash(&data[offset], length - offset, digest, |
| 67 | hmackey); |
| 68 | |
| 69 | if (status) { |
| 70 | printf("HMAC-SHA256 hash error\n"); |
| 71 | return 0; |
| 72 | } |
| 73 | |
| 74 | return 32; |
| 75 | } |