aead_demo.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /**
  2. * PSA API multi-part AEAD demonstration.
  3. *
  4. * This program AEAD-encrypts a message, using the algorithm and key size
  5. * specified on the command line, using the multi-part API.
  6. *
  7. * It comes with a companion program cipher/cipher_aead_demo.c, which does the
  8. * same operations with the legacy Cipher API. The goal is that comparing the
  9. * two programs will help people migrating to the PSA Crypto API.
  10. *
  11. * When used with multi-part AEAD operations, the `mbedtls_cipher_context`
  12. * serves a triple purpose (1) hold the key, (2) store the algorithm when no
  13. * operation is active, and (3) save progress information for the current
  14. * operation. With PSA those roles are held by disinct objects: (1) a
  15. * psa_key_id_t to hold the key, a (2) psa_algorithm_t to represent the
  16. * algorithm, and (3) a psa_operation_t for multi-part progress.
  17. *
  18. * On the other hand, with PSA, the algorithms encodes the desired tag length;
  19. * with Cipher the desired tag length needs to be tracked separately.
  20. *
  21. * This program and its companion cipher/cipher_aead_demo.c illustrate this by
  22. * doing the same sequence of multi-part AEAD computation with both APIs;
  23. * looking at the two side by side should make the differences and
  24. * similarities clear.
  25. */
  26. /*
  27. * Copyright The Mbed TLS Contributors
  28. * SPDX-License-Identifier: Apache-2.0
  29. *
  30. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  31. * not use this file except in compliance with the License.
  32. * You may obtain a copy of the License at
  33. *
  34. * http://www.apache.org/licenses/LICENSE-2.0
  35. *
  36. * Unless required by applicable law or agreed to in writing, software
  37. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  38. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  39. * See the License for the specific language governing permissions and
  40. * limitations under the License.
  41. */
  42. /* First include Mbed TLS headers to get the Mbed TLS configuration and
  43. * platform definitions that we'll use in this program. Also include
  44. * standard C headers for functions we'll use here. */
  45. #include "mbedtls/build_info.h"
  46. #include "psa/crypto.h"
  47. #include <stdlib.h>
  48. #include <stdio.h>
  49. #include <string.h>
  50. /* If the build options we need are not enabled, compile a placeholder. */
  51. #if !defined(MBEDTLS_PSA_CRYPTO_C) || \
  52. !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_GCM_C) || \
  53. !defined(MBEDTLS_CHACHAPOLY_C) || \
  54. defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
  55. int main(void)
  56. {
  57. printf("MBEDTLS_PSA_CRYPTO_C and/or "
  58. "MBEDTLS_AES_C and/or MBEDTLS_GCM_C and/or "
  59. "MBEDTLS_CHACHAPOLY_C not defined, and/or "
  60. "MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER defined\r\n");
  61. return 0;
  62. }
  63. #else
  64. /* The real program starts here. */
  65. const char usage[] =
  66. "Usage: aead_demo [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
  67. /* Dummy data for encryption: IV/nonce, additional data, 2-part message */
  68. const unsigned char iv1[12] = { 0x00 };
  69. const unsigned char add_data1[] = { 0x01, 0x02 };
  70. const unsigned char msg1_part1[] = { 0x03, 0x04 };
  71. const unsigned char msg1_part2[] = { 0x05, 0x06, 0x07 };
  72. /* Dummy data (2nd message) */
  73. const unsigned char iv2[12] = { 0x10 };
  74. const unsigned char add_data2[] = { 0x11, 0x12 };
  75. const unsigned char msg2_part1[] = { 0x13, 0x14 };
  76. const unsigned char msg2_part2[] = { 0x15, 0x16, 0x17 };
  77. /* Maximum total size of the messages */
  78. #define MSG1_SIZE (sizeof(msg1_part1) + sizeof(msg1_part2))
  79. #define MSG2_SIZE (sizeof(msg2_part1) + sizeof(msg2_part2))
  80. #define MSG_MAX_SIZE (MSG1_SIZE > MSG2_SIZE ? MSG1_SIZE : MSG2_SIZE)
  81. /* Dummy key material - never do this in production!
  82. * 32-byte is enough to all the key size supported by this program. */
  83. const unsigned char key_bytes[32] = { 0x2a };
  84. /* Print the contents of a buffer in hex */
  85. void print_buf(const char *title, uint8_t *buf, size_t len)
  86. {
  87. printf("%s:", title);
  88. for (size_t i = 0; i < len; i++) {
  89. printf(" %02x", buf[i]);
  90. }
  91. printf("\n");
  92. }
  93. /* Run a PSA function and bail out if it fails.
  94. * The symbolic name of the error code can be recovered using:
  95. * programs/psa/psa_constant_name status <value> */
  96. #define PSA_CHECK(expr) \
  97. do \
  98. { \
  99. status = (expr); \
  100. if (status != PSA_SUCCESS) \
  101. { \
  102. printf("Error %d at line %d: %s\n", \
  103. (int) status, \
  104. __LINE__, \
  105. #expr); \
  106. goto exit; \
  107. } \
  108. } \
  109. while (0)
  110. /*
  111. * Prepare encryption material:
  112. * - interpret command-line argument
  113. * - set up key
  114. * - outputs: key and algorithm, which together hold all the information
  115. */
  116. static psa_status_t aead_prepare(const char *info,
  117. psa_key_id_t *key,
  118. psa_algorithm_t *alg)
  119. {
  120. psa_status_t status;
  121. /* Convert arg to alg + key_bits + key_type */
  122. size_t key_bits;
  123. psa_key_type_t key_type;
  124. if (strcmp(info, "aes128-gcm") == 0) {
  125. *alg = PSA_ALG_GCM;
  126. key_bits = 128;
  127. key_type = PSA_KEY_TYPE_AES;
  128. } else if (strcmp(info, "aes256-gcm") == 0) {
  129. *alg = PSA_ALG_GCM;
  130. key_bits = 256;
  131. key_type = PSA_KEY_TYPE_AES;
  132. } else if (strcmp(info, "aes128-gcm_8") == 0) {
  133. *alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 8);
  134. key_bits = 128;
  135. key_type = PSA_KEY_TYPE_AES;
  136. } else if (strcmp(info, "chachapoly") == 0) {
  137. *alg = PSA_ALG_CHACHA20_POLY1305;
  138. key_bits = 256;
  139. key_type = PSA_KEY_TYPE_CHACHA20;
  140. } else {
  141. puts(usage);
  142. return PSA_ERROR_INVALID_ARGUMENT;
  143. }
  144. /* Prepare key attributes */
  145. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  146. psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
  147. psa_set_key_algorithm(&attributes, *alg);
  148. psa_set_key_type(&attributes, key_type);
  149. psa_set_key_bits(&attributes, key_bits); // optional
  150. /* Import key */
  151. PSA_CHECK(psa_import_key(&attributes, key_bytes, key_bits / 8, key));
  152. exit:
  153. return status;
  154. }
  155. /*
  156. * Print out some information.
  157. *
  158. * All of this information was present in the command line argument, but his
  159. * function demonstrates how each piece can be recovered from (key, alg).
  160. */
  161. static void aead_info(psa_key_id_t key, psa_algorithm_t alg)
  162. {
  163. psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
  164. (void) psa_get_key_attributes(key, &attr);
  165. psa_key_type_t key_type = psa_get_key_type(&attr);
  166. size_t key_bits = psa_get_key_bits(&attr);
  167. psa_algorithm_t base_alg = PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
  168. size_t tag_len = PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg);
  169. const char *type_str = key_type == PSA_KEY_TYPE_AES ? "AES"
  170. : key_type == PSA_KEY_TYPE_CHACHA20 ? "Chacha"
  171. : "???";
  172. const char *base_str = base_alg == PSA_ALG_GCM ? "GCM"
  173. : base_alg == PSA_ALG_CHACHA20_POLY1305 ? "ChachaPoly"
  174. : "???";
  175. printf("%s, %u, %s, %u\n",
  176. type_str, (unsigned) key_bits, base_str, (unsigned) tag_len);
  177. }
  178. /*
  179. * Encrypt a 2-part message.
  180. */
  181. static int aead_encrypt(psa_key_id_t key, psa_algorithm_t alg,
  182. const unsigned char *iv, size_t iv_len,
  183. const unsigned char *ad, size_t ad_len,
  184. const unsigned char *part1, size_t part1_len,
  185. const unsigned char *part2, size_t part2_len)
  186. {
  187. psa_status_t status;
  188. size_t olen, olen_tag;
  189. unsigned char out[PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(MSG_MAX_SIZE)];
  190. unsigned char *p = out, *end = out + sizeof(out);
  191. unsigned char tag[PSA_AEAD_TAG_MAX_SIZE];
  192. psa_aead_operation_t op = PSA_AEAD_OPERATION_INIT;
  193. PSA_CHECK(psa_aead_encrypt_setup(&op, key, alg));
  194. PSA_CHECK(psa_aead_set_nonce(&op, iv, iv_len));
  195. PSA_CHECK(psa_aead_update_ad(&op, ad, ad_len));
  196. PSA_CHECK(psa_aead_update(&op, part1, part1_len, p, end - p, &olen));
  197. p += olen;
  198. PSA_CHECK(psa_aead_update(&op, part2, part2_len, p, end - p, &olen));
  199. p += olen;
  200. PSA_CHECK(psa_aead_finish(&op, p, end - p, &olen,
  201. tag, sizeof(tag), &olen_tag));
  202. p += olen;
  203. memcpy(p, tag, olen_tag);
  204. p += olen_tag;
  205. olen = p - out;
  206. print_buf("out", out, olen);
  207. exit:
  208. psa_aead_abort(&op); // required on errors, harmless on success
  209. return status;
  210. }
  211. /*
  212. * AEAD demo: set up key/alg, print out info, encrypt messages.
  213. */
  214. static psa_status_t aead_demo(const char *info)
  215. {
  216. psa_status_t status;
  217. psa_key_id_t key;
  218. psa_algorithm_t alg;
  219. PSA_CHECK(aead_prepare(info, &key, &alg));
  220. aead_info(key, alg);
  221. PSA_CHECK(aead_encrypt(key, alg,
  222. iv1, sizeof(iv1), add_data1, sizeof(add_data1),
  223. msg1_part1, sizeof(msg1_part1),
  224. msg1_part2, sizeof(msg1_part2)));
  225. PSA_CHECK(aead_encrypt(key, alg,
  226. iv2, sizeof(iv2), add_data2, sizeof(add_data2),
  227. msg2_part1, sizeof(msg2_part1),
  228. msg2_part2, sizeof(msg2_part2)));
  229. exit:
  230. psa_destroy_key(key);
  231. return status;
  232. }
  233. /*
  234. * Main function
  235. */
  236. int main(int argc, char **argv)
  237. {
  238. psa_status_t status = PSA_SUCCESS;
  239. /* Check usage */
  240. if (argc != 2) {
  241. puts(usage);
  242. return EXIT_FAILURE;
  243. }
  244. /* Initialize the PSA crypto library. */
  245. PSA_CHECK(psa_crypto_init());
  246. /* Run the demo */
  247. PSA_CHECK(aead_demo(argv[1]));
  248. /* Deinitialize the PSA crypto library. */
  249. mbedtls_psa_crypto_free();
  250. exit:
  251. return status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
  252. }
  253. #endif