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
24  *
25  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
26  *  not use this file except in compliance with the License.
27  *  You may obtain a copy of the License at
28  *
29  *  http://www.apache.org/licenses/LICENSE-2.0
30  *
31  *  Unless required by applicable law or agreed to in writing, software
32  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
33  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
34  *  See the License for the specific language governing permissions and
35  *  limitations under the License.
36  */
37 
38 /* First include Mbed TLS headers to get the Mbed TLS configuration and
39  * platform definitions that we'll use in this program. Also include
40  * standard C headers for functions we'll use here. */
41 #include "mbedtls/build_info.h"
42 
43 #include "psa/crypto.h"
44 
45 #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
46 
47 #include <stdlib.h>
48 #include <stdio.h>
49 
50 /* If the build options we need are not enabled, compile a placeholder. */
51 #if !defined(MBEDTLS_PSA_CRYPTO_C) || \
52     defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
main(void)53 int main(void)
54 {
55     printf("MBEDTLS_PSA_CRYPTO_C not defined, "
56            "and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER defined\r\n");
57     return 0;
58 }
59 #else
60 
61 /* The real program starts here. */
62 
63 /* Dummy inputs for HMAC */
64 const unsigned char msg1_part1[] = { 0x01, 0x02 };
65 const unsigned char msg1_part2[] = { 0x03, 0x04 };
66 const unsigned char msg2_part1[] = { 0x05, 0x05 };
67 const unsigned char msg2_part2[] = { 0x06, 0x06 };
68 
69 /* Dummy key material - never do this in production!
70  * This example program uses SHA-256, so a 32-byte key makes sense. */
71 const unsigned char key_bytes[32] = { 0 };
72 
73 /* Print the contents of a buffer in hex */
print_buf(const char * title,uint8_t * buf,size_t len)74 void print_buf(const char *title, uint8_t *buf, size_t len)
75 {
76     printf("%s:", title);
77     for (size_t i = 0; i < len; i++) {
78         printf(" %02x", buf[i]);
79     }
80     printf("\n");
81 }
82 
83 /* Run a PSA function and bail out if it fails.
84  * The symbolic name of the error code can be recovered using:
85  * programs/psa/psa_constant_name status <value> */
86 #define PSA_CHECK(expr)                                       \
87     do                                                          \
88     {                                                           \
89         status = (expr);                                      \
90         if (status != PSA_SUCCESS)                             \
91         {                                                       \
92             printf("Error %d at line %d: %s\n",                \
93                    (int) status,                               \
94                    __LINE__,                                   \
95                    #expr);                                    \
96             goto exit;                                          \
97         }                                                       \
98     }                                                           \
99     while (0)
100 
101 /*
102  * This function demonstrates computation of the HMAC of two messages using
103  * the multipart API.
104  */
hmac_demo(void)105 psa_status_t hmac_demo(void)
106 {
107     psa_status_t status;
108     const psa_algorithm_t alg = PSA_ALG_HMAC(PSA_ALG_SHA_256);
109     uint8_t out[PSA_MAC_MAX_SIZE]; // safe but not optimal
110     /* PSA_MAC_LENGTH(PSA_KEY_TYPE_HMAC, 8 * sizeof( key_bytes ), alg)
111      * should work but see https://github.com/Mbed-TLS/mbedtls/issues/4320 */
112 
113     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
114     psa_key_id_t key = 0;
115 
116     /* prepare key */
117     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
118     psa_set_key_algorithm(&attributes, alg);
119     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
120     psa_set_key_bits(&attributes, 8 * sizeof(key_bytes));     // optional
121 
122     status = psa_import_key(&attributes,
123                             key_bytes, sizeof(key_bytes), &key);
124     if (status != PSA_SUCCESS) {
125         return status;
126     }
127 
128     /* prepare operation */
129     psa_mac_operation_t op = PSA_MAC_OPERATION_INIT;
130     size_t out_len = 0;
131 
132     /* compute HMAC(key, msg1_part1 | msg1_part2) */
133     PSA_CHECK(psa_mac_sign_setup(&op, key, alg));
134     PSA_CHECK(psa_mac_update(&op, msg1_part1, sizeof(msg1_part1)));
135     PSA_CHECK(psa_mac_update(&op, msg1_part2, sizeof(msg1_part2)));
136     PSA_CHECK(psa_mac_sign_finish(&op, out, sizeof(out), &out_len));
137     print_buf("msg1", out, out_len);
138 
139     /* compute HMAC(key, msg2_part1 | msg2_part2) */
140     PSA_CHECK(psa_mac_sign_setup(&op, key, alg));
141     PSA_CHECK(psa_mac_update(&op, msg2_part1, sizeof(msg2_part1)));
142     PSA_CHECK(psa_mac_update(&op, msg2_part2, sizeof(msg2_part2)));
143     PSA_CHECK(psa_mac_sign_finish(&op, out, sizeof(out), &out_len));
144     print_buf("msg2", out, out_len);
145 
146 exit:
147     psa_mac_abort(&op);   // needed on error, harmless on success
148     psa_destroy_key(key);
149     mbedtls_platform_zeroize(out, sizeof(out));
150 
151     return status;
152 }
153 
main(void)154 int main(void)
155 {
156     psa_status_t status = PSA_SUCCESS;
157 
158     /* Initialize the PSA crypto library. */
159     PSA_CHECK(psa_crypto_init());
160 
161     /* Run the demo */
162     PSA_CHECK(hmac_demo());
163 
164     /* Deinitialize the PSA crypto library. */
165     mbedtls_psa_crypto_free();
166 
167 exit:
168     return status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
169 }
170 
171 #endif
172