quickjs-tart

quickjs-based runtime for wallet-core logic
Log | Files | Refs | README | LICENSE

hmac_demo.c (5696B)


      1 /**
      2  * PSA API multi-part HMAC demonstration.
      3  *
      4  * This programs computes the HMAC of two messages using the multi-part API.
      5  *
      6  * It comes with a companion program hash/md_hmac_demo.c, which does the same
      7  * operations with the legacy MD API. The goal is that comparing the two
      8  * programs will help people migrating to the PSA Crypto API.
      9  *
     10  * When it comes to multi-part HMAC operations, the `mbedtls_md_context`
     11  * serves a dual purpose (1) hold the key, and (2) save progress information
     12  * for the current operation. With PSA those roles are held by two disinct
     13  * objects: (1) a psa_key_id_t to hold the key, and (2) a psa_operation_t for
     14  * multi-part progress.
     15  *
     16  * This program and its companion hash/md_hmac_demo.c illustrate this by doing
     17  * the same sequence of multi-part HMAC computation with both APIs; looking at
     18  * the two side by side should make the differences and similarities clear.
     19  */
     20 
     21 /*
     22  *  Copyright The Mbed TLS Contributors
     23  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
     24  */
     25 
     26 /* First include Mbed TLS headers to get the Mbed TLS configuration and
     27  * platform definitions that we'll use in this program. Also include
     28  * standard C headers for functions we'll use here. */
     29 #include "mbedtls/build_info.h"
     30 
     31 #include "psa/crypto.h"
     32 
     33 #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
     34 
     35 #include <stdlib.h>
     36 #include <stdio.h>
     37 
     38 /* If the build options we need are not enabled, compile a placeholder. */
     39 #if !defined(MBEDTLS_PSA_CRYPTO_C) || \
     40     defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
     41 int main(void)
     42 {
     43     printf("MBEDTLS_PSA_CRYPTO_C not defined, "
     44            "and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER defined\r\n");
     45     return 0;
     46 }
     47 #else
     48 
     49 /* The real program starts here. */
     50 
     51 /* Dummy inputs for HMAC */
     52 const unsigned char msg1_part1[] = { 0x01, 0x02 };
     53 const unsigned char msg1_part2[] = { 0x03, 0x04 };
     54 const unsigned char msg2_part1[] = { 0x05, 0x05 };
     55 const unsigned char msg2_part2[] = { 0x06, 0x06 };
     56 
     57 /* Dummy key material - never do this in production!
     58  * This example program uses SHA-256, so a 32-byte key makes sense. */
     59 const unsigned char key_bytes[32] = { 0 };
     60 
     61 /* Print the contents of a buffer in hex */
     62 static void print_buf(const char *title, uint8_t *buf, size_t len)
     63 {
     64     printf("%s:", title);
     65     for (size_t i = 0; i < len; i++) {
     66         printf(" %02x", buf[i]);
     67     }
     68     printf("\n");
     69 }
     70 
     71 /* Run a PSA function and bail out if it fails.
     72  * The symbolic name of the error code can be recovered using:
     73  * programs/psa/psa_constant_name status <value> */
     74 #define PSA_CHECK(expr)                                       \
     75     do                                                          \
     76     {                                                           \
     77         status = (expr);                                      \
     78         if (status != PSA_SUCCESS)                             \
     79         {                                                       \
     80             printf("Error %d at line %d: %s\n",                \
     81                    (int) status,                               \
     82                    __LINE__,                                   \
     83                    #expr);                                    \
     84             goto exit;                                          \
     85         }                                                       \
     86     }                                                           \
     87     while (0)
     88 
     89 /*
     90  * This function demonstrates computation of the HMAC of two messages using
     91  * the multipart API.
     92  */
     93 static psa_status_t hmac_demo(void)
     94 {
     95     psa_status_t status;
     96     const psa_algorithm_t alg = PSA_ALG_HMAC(PSA_ALG_SHA_256);
     97     uint8_t out[PSA_MAC_MAX_SIZE]; // safe but not optimal
     98     /* PSA_MAC_LENGTH(PSA_KEY_TYPE_HMAC, 8 * sizeof( key_bytes ), alg)
     99      * should work but see https://github.com/Mbed-TLS/mbedtls/issues/4320 */
    100 
    101     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
    102     psa_key_id_t key = 0;
    103 
    104     /* prepare key */
    105     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
    106     psa_set_key_algorithm(&attributes, alg);
    107     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
    108     psa_set_key_bits(&attributes, 8 * sizeof(key_bytes));     // optional
    109 
    110     status = psa_import_key(&attributes,
    111                             key_bytes, sizeof(key_bytes), &key);
    112     if (status != PSA_SUCCESS) {
    113         return status;
    114     }
    115 
    116     /* prepare operation */
    117     psa_mac_operation_t op = PSA_MAC_OPERATION_INIT;
    118     size_t out_len = 0;
    119 
    120     /* compute HMAC(key, msg1_part1 | msg1_part2) */
    121     PSA_CHECK(psa_mac_sign_setup(&op, key, alg));
    122     PSA_CHECK(psa_mac_update(&op, msg1_part1, sizeof(msg1_part1)));
    123     PSA_CHECK(psa_mac_update(&op, msg1_part2, sizeof(msg1_part2)));
    124     PSA_CHECK(psa_mac_sign_finish(&op, out, sizeof(out), &out_len));
    125     print_buf("msg1", out, out_len);
    126 
    127     /* compute HMAC(key, msg2_part1 | msg2_part2) */
    128     PSA_CHECK(psa_mac_sign_setup(&op, key, alg));
    129     PSA_CHECK(psa_mac_update(&op, msg2_part1, sizeof(msg2_part1)));
    130     PSA_CHECK(psa_mac_update(&op, msg2_part2, sizeof(msg2_part2)));
    131     PSA_CHECK(psa_mac_sign_finish(&op, out, sizeof(out), &out_len));
    132     print_buf("msg2", out, out_len);
    133 
    134 exit:
    135     psa_mac_abort(&op);   // needed on error, harmless on success
    136     psa_destroy_key(key);
    137     mbedtls_platform_zeroize(out, sizeof(out));
    138 
    139     return status;
    140 }
    141 
    142 int main(void)
    143 {
    144     psa_status_t status = PSA_SUCCESS;
    145 
    146     /* Initialize the PSA crypto library. */
    147     PSA_CHECK(psa_crypto_init());
    148 
    149     /* Run the demo */
    150     PSA_CHECK(hmac_demo());
    151 
    152     /* Deinitialize the PSA crypto library. */
    153     mbedtls_psa_crypto_free();
    154 
    155 exit:
    156     return status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
    157 }
    158 
    159 #endif