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 454 : bool hmac_sha512(uint8_t *out, 32 : const uint8_t *key, 33 : const unsigned int key_length, 34 : const uint8_t *text, 35 : const unsigned int text_length) { 36 : mbedtls_md_context_t ctx; 37 : int use_hmac; 38 : const mbedtls_md_info_t *md_info; 39 : 40 454 : mbedtls_md_init(&ctx); 41 454 : md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512); 42 454 : if (!md_info) { 43 : LOG("Error: SHA-512 not supported\n"); 44 0 : goto hmac_sha512_error; 45 : } 46 : 47 454 : use_hmac = 1; 48 454 : if (mbedtls_md_setup(&ctx, md_info, use_hmac) != 0) { 49 0 : goto hmac_sha512_error; 50 : } 51 : 52 454 : if (mbedtls_md_hmac_starts(&ctx, key, key_length) != 0) { 53 0 : goto hmac_sha512_error; 54 : } 55 : 56 454 : if (mbedtls_md_hmac_update(&ctx, text, text_length) != 0) { 57 0 : goto hmac_sha512_error; 58 : } 59 : 60 454 : if (mbedtls_md_hmac_finish(&ctx, out) != 0) { 61 0 : goto hmac_sha512_error; 62 : } 63 : 64 454 : mbedtls_md_free(&ctx); 65 454 : return true; 66 : 67 0 : hmac_sha512_error: 68 : LOG("Error: failed to compute HMAC-SHA512\n"); 69 0 : mbedtls_md_free(&ctx); 70 0 : return false; 71 : }