cipher_aead_demo.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /**
  2. * Cipher 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 psa/aead_demo.c, which does the same
  8. * operations with the PSA Crypto API. The goal is that comparing the two
  9. * 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 psa/aead_demo.c illustrate this by doing the
  22. * same sequence of multi-part AEAD computation with both APIs; looking at the
  23. * two side by side should make the differences and similarities clear.
  24. */
  25. /*
  26. * Copyright The Mbed TLS Contributors
  27. * SPDX-License-Identifier: Apache-2.0
  28. *
  29. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  30. * not use this file except in compliance with the License.
  31. * You may obtain a copy of the License at
  32. *
  33. * http://www.apache.org/licenses/LICENSE-2.0
  34. *
  35. * Unless required by applicable law or agreed to in writing, software
  36. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  37. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38. * See the License for the specific language governing permissions and
  39. * limitations under the License.
  40. */
  41. /* First include Mbed TLS headers to get the Mbed TLS configuration and
  42. * platform definitions that we'll use in this program. Also include
  43. * standard C headers for functions we'll use here. */
  44. #include "mbedtls/build_info.h"
  45. #include "mbedtls/cipher.h"
  46. #include <stdlib.h>
  47. #include <stdio.h>
  48. #include <string.h>
  49. /* If the build options we need are not enabled, compile a placeholder. */
  50. #if !defined(MBEDTLS_CIPHER_C) || \
  51. !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_GCM_C) || \
  52. !defined(MBEDTLS_CHACHAPOLY_C)
  53. int main(void)
  54. {
  55. printf("MBEDTLS_MD_C and/or "
  56. "MBEDTLS_AES_C and/or MBEDTLS_GCM_C and/or "
  57. "MBEDTLS_CHACHAPOLY_C not defined\r\n");
  58. return 0;
  59. }
  60. #else
  61. /* The real program starts here. */
  62. const char usage[] =
  63. "Usage: cipher_aead_demo [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
  64. /* Dummy data for encryption: IV/nonce, additional data, 2-part message */
  65. const unsigned char iv1[12] = { 0x00 };
  66. const unsigned char add_data1[] = { 0x01, 0x02 };
  67. const unsigned char msg1_part1[] = { 0x03, 0x04 };
  68. const unsigned char msg1_part2[] = { 0x05, 0x06, 0x07 };
  69. /* Dummy data (2nd message) */
  70. const unsigned char iv2[12] = { 0x10 };
  71. const unsigned char add_data2[] = { 0x11, 0x12 };
  72. const unsigned char msg2_part1[] = { 0x13, 0x14 };
  73. const unsigned char msg2_part2[] = { 0x15, 0x16, 0x17 };
  74. /* Maximum total size of the messages */
  75. #define MSG1_SIZE (sizeof(msg1_part1) + sizeof(msg1_part2))
  76. #define MSG2_SIZE (sizeof(msg2_part1) + sizeof(msg2_part2))
  77. #define MSG_MAX_SIZE (MSG1_SIZE > MSG2_SIZE ? MSG1_SIZE : MSG2_SIZE)
  78. /* Dummy key material - never do this in production!
  79. * 32-byte is enough to all the key size supported by this program. */
  80. const unsigned char key_bytes[32] = { 0x2a };
  81. /* Print the contents of a buffer in hex */
  82. void print_buf(const char *title, unsigned char *buf, size_t len)
  83. {
  84. printf("%s:", title);
  85. for (size_t i = 0; i < len; i++) {
  86. printf(" %02x", buf[i]);
  87. }
  88. printf("\n");
  89. }
  90. /* Run an Mbed TLS function and bail out if it fails.
  91. * A string description of the error code can be recovered with:
  92. * programs/util/strerror <value> */
  93. #define CHK(expr) \
  94. do \
  95. { \
  96. ret = (expr); \
  97. if (ret != 0) \
  98. { \
  99. printf("Error %d at line %d: %s\n", \
  100. ret, \
  101. __LINE__, \
  102. #expr); \
  103. goto exit; \
  104. } \
  105. } while (0)
  106. /*
  107. * Prepare encryption material:
  108. * - interpret command-line argument
  109. * - set up key
  110. * - outputs: context and tag length, which together hold all the information
  111. */
  112. static int aead_prepare(const char *info,
  113. mbedtls_cipher_context_t *ctx,
  114. size_t *tag_len)
  115. {
  116. int ret;
  117. /* Convert arg to type + tag_len */
  118. mbedtls_cipher_type_t type;
  119. if (strcmp(info, "aes128-gcm") == 0) {
  120. type = MBEDTLS_CIPHER_AES_128_GCM;
  121. *tag_len = 16;
  122. } else if (strcmp(info, "aes256-gcm") == 0) {
  123. type = MBEDTLS_CIPHER_AES_256_GCM;
  124. *tag_len = 16;
  125. } else if (strcmp(info, "aes128-gcm_8") == 0) {
  126. type = MBEDTLS_CIPHER_AES_128_GCM;
  127. *tag_len = 8;
  128. } else if (strcmp(info, "chachapoly") == 0) {
  129. type = MBEDTLS_CIPHER_CHACHA20_POLY1305;
  130. *tag_len = 16;
  131. } else {
  132. puts(usage);
  133. return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
  134. }
  135. /* Prepare context for the given type */
  136. CHK(mbedtls_cipher_setup(ctx,
  137. mbedtls_cipher_info_from_type(type)));
  138. /* Import key */
  139. int key_len = mbedtls_cipher_get_key_bitlen(ctx);
  140. CHK(mbedtls_cipher_setkey(ctx, key_bytes, key_len, MBEDTLS_ENCRYPT));
  141. exit:
  142. return ret;
  143. }
  144. /*
  145. * Print out some information.
  146. *
  147. * All of this information was present in the command line argument, but his
  148. * function demonstrates how each piece can be recovered from (ctx, tag_len).
  149. */
  150. static void aead_info(const mbedtls_cipher_context_t *ctx, size_t tag_len)
  151. {
  152. mbedtls_cipher_type_t type = mbedtls_cipher_get_type(ctx);
  153. const mbedtls_cipher_info_t *info = mbedtls_cipher_info_from_type(type);
  154. const char *ciph = mbedtls_cipher_info_get_name(info);
  155. int key_bits = mbedtls_cipher_get_key_bitlen(ctx);
  156. mbedtls_cipher_mode_t mode = mbedtls_cipher_get_cipher_mode(ctx);
  157. const char *mode_str = mode == MBEDTLS_MODE_GCM ? "GCM"
  158. : mode == MBEDTLS_MODE_CHACHAPOLY ? "ChachaPoly"
  159. : "???";
  160. printf("%s, %d, %s, %u\n",
  161. ciph, key_bits, mode_str, (unsigned) tag_len);
  162. }
  163. /*
  164. * Encrypt a 2-part message.
  165. */
  166. static int aead_encrypt(mbedtls_cipher_context_t *ctx, size_t tag_len,
  167. const unsigned char *iv, size_t iv_len,
  168. const unsigned char *ad, size_t ad_len,
  169. const unsigned char *part1, size_t part1_len,
  170. const unsigned char *part2, size_t part2_len)
  171. {
  172. int ret;
  173. size_t olen;
  174. #define MAX_TAG_LENGTH 16
  175. unsigned char out[MSG_MAX_SIZE + MAX_TAG_LENGTH];
  176. unsigned char *p = out;
  177. CHK(mbedtls_cipher_set_iv(ctx, iv, iv_len));
  178. CHK(mbedtls_cipher_reset(ctx));
  179. CHK(mbedtls_cipher_update_ad(ctx, ad, ad_len));
  180. CHK(mbedtls_cipher_update(ctx, part1, part1_len, p, &olen));
  181. p += olen;
  182. CHK(mbedtls_cipher_update(ctx, part2, part2_len, p, &olen));
  183. p += olen;
  184. CHK(mbedtls_cipher_finish(ctx, p, &olen));
  185. p += olen;
  186. CHK(mbedtls_cipher_write_tag(ctx, p, tag_len));
  187. p += tag_len;
  188. olen = p - out;
  189. print_buf("out", out, olen);
  190. exit:
  191. return ret;
  192. }
  193. /*
  194. * AEAD demo: set up key/alg, print out info, encrypt messages.
  195. */
  196. static int aead_demo(const char *info)
  197. {
  198. int ret = 0;
  199. mbedtls_cipher_context_t ctx;
  200. size_t tag_len;
  201. mbedtls_cipher_init(&ctx);
  202. CHK(aead_prepare(info, &ctx, &tag_len));
  203. aead_info(&ctx, tag_len);
  204. CHK(aead_encrypt(&ctx, tag_len,
  205. iv1, sizeof(iv1), add_data1, sizeof(add_data1),
  206. msg1_part1, sizeof(msg1_part1),
  207. msg1_part2, sizeof(msg1_part2)));
  208. CHK(aead_encrypt(&ctx, tag_len,
  209. iv2, sizeof(iv2), add_data2, sizeof(add_data2),
  210. msg2_part1, sizeof(msg2_part1),
  211. msg2_part2, sizeof(msg2_part2)));
  212. exit:
  213. mbedtls_cipher_free(&ctx);
  214. return ret;
  215. }
  216. /*
  217. * Main function
  218. */
  219. int main(int argc, char **argv)
  220. {
  221. /* Check usage */
  222. if (argc != 2) {
  223. puts(usage);
  224. return 1;
  225. }
  226. int ret;
  227. /* Run the demo */
  228. CHK(aead_demo(argv[1]));
  229. exit:
  230. return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
  231. }
  232. #endif