Line data Source code
1 : /** 2 : * The MIT License (MIT) 3 : * 4 : * Copyright (c) 2021 RSK Labs Ltd 5 : * 6 : * Permission is hereby granted, free of charge, to any person obtaining a copy 7 : * of this software and associated documentation files (the "Software"), to 8 : * deal in the Software without restriction, including without limitation the 9 : * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 10 : * sell copies of the Software, and to permit persons to whom the Software is 11 : * furnished to do so, subject to the following conditions: 12 : * 13 : * The above copyright notice and this permission notice shall be included in 14 : * all copies or substantial portions of the Software. 15 : * 16 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 : * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 : * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 : * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 : * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 : * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 22 : * IN THE SOFTWARE. 23 : */ 24 : 25 : #include "hal/log.h" 26 : #include "endian.h" 27 : #include "hmac_sha512.h" 28 : 29 : #include <mbedtls/md.h> 30 : 31 456 : bool hmac_sha512(uint8_t *out, 32 : const size_t out_length, 33 : const uint8_t *key, 34 : const unsigned int key_length, 35 : const uint8_t *text, 36 : const unsigned int text_length) { 37 : mbedtls_md_context_t ctx; 38 : int use_hmac; 39 : const mbedtls_md_info_t *md_info; 40 : 41 456 : if (out_length < SHA512_HASH_LENGTH) { 42 : LOG("Error: output buffer too small\n"); 43 1 : return false; 44 : } 45 : 46 455 : mbedtls_md_init(&ctx); 47 455 : md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512); 48 455 : if (!md_info) { 49 : LOG("Error: SHA-512 not supported\n"); 50 0 : goto hmac_sha512_error; 51 : } 52 : 53 455 : use_hmac = 1; 54 455 : if (mbedtls_md_setup(&ctx, md_info, use_hmac) != 0) { 55 0 : goto hmac_sha512_error; 56 : } 57 : 58 455 : if (mbedtls_md_hmac_starts(&ctx, key, key_length) != 0) { 59 0 : goto hmac_sha512_error; 60 : } 61 : 62 455 : if (mbedtls_md_hmac_update(&ctx, text, text_length) != 0) { 63 0 : goto hmac_sha512_error; 64 : } 65 : 66 455 : if (mbedtls_md_hmac_finish(&ctx, out) != 0) { 67 0 : goto hmac_sha512_error; 68 : } 69 : 70 455 : mbedtls_md_free(&ctx); 71 455 : return true; 72 : 73 0 : hmac_sha512_error: 74 : LOG("Error: failed to compute HMAC-SHA512\n"); 75 0 : mbedtls_md_free(&ctx); 76 0 : return false; 77 : }