main.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*
  2. * Hello world example of using the authenticated encryption with mbed TLS
  3. *
  4. * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * This file is part of mbed TLS (https://tls.mbed.org)
  20. */
  21. #include "mbedtls/cipher.h"
  22. #include "mbedtls/entropy.h"
  23. #include "mbedtls/ctr_drbg.h"
  24. #include <stdio.h>
  25. #include <string.h>
  26. static void print_hex(const char *title, const unsigned char buf[], size_t len)
  27. {
  28. printf("%s: ", title);
  29. for (size_t i = 0; i < len; i++)
  30. printf("%02x", buf[i]);
  31. printf("\r\n");
  32. }
  33. /*
  34. * The pre-shared key. Should be generated randomly and be unique to the
  35. * device/channel/etc. Just used a fixed on here for simplicity.
  36. */
  37. static const unsigned char secret_key[16] = {
  38. 0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
  39. 0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
  40. };
  41. static int example(void)
  42. {
  43. /* message that should be protected */
  44. const char message[] = "Some things are better left unread";
  45. /* metadata transmitted in the clear but authenticated */
  46. const char metadata[] = "eg sequence number, routing info";
  47. /* ciphertext buffer large enough to hold message + nonce + tag */
  48. unsigned char ciphertext[128] = { 0 };
  49. int ret;
  50. printf("\r\n\r\n");
  51. print_hex("plaintext message", (unsigned char *) message, sizeof message);
  52. /*
  53. * Setup random number generator
  54. * (Note: later this might be done automatically.)
  55. */
  56. mbedtls_entropy_context entropy; /* entropy pool for seeding PRNG */
  57. mbedtls_ctr_drbg_context drbg; /* pseudo-random generator */
  58. mbedtls_entropy_init(&entropy);
  59. mbedtls_ctr_drbg_init(&drbg);
  60. /* Seed the PRNG using the entropy pool, and throw in our secret key as an
  61. * additional source of randomness. */
  62. ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
  63. secret_key, sizeof (secret_key));
  64. if (ret != 0) {
  65. printf("mbedtls_ctr_drbg_init() returned -0x%04X\r\n", -ret);
  66. return 1;
  67. }
  68. /*
  69. * Setup AES-CCM contex
  70. */
  71. mbedtls_cipher_context_t ctx;
  72. mbedtls_cipher_init(&ctx);
  73. ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
  74. if (ret != 0) {
  75. printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
  76. return 1;
  77. }
  78. ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
  79. if (ret != 0) {
  80. printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
  81. return 1;
  82. }
  83. /*
  84. * Encrypt-authenticate the message and authenticate additional data
  85. *
  86. * First generate a random 8-byte nonce.
  87. * Put it directly in the output buffer as the recipient will need it.
  88. *
  89. * Warning: you must never re-use the same (key, nonce) pair. One of the
  90. * best ways to ensure this to use a counter for the nonce. However this
  91. * means you should save the counter accross rebots, if the key is a
  92. * long-term one. The alternative we choose here is to generate the nonce
  93. * randomly. However it only works if you have a good source of
  94. * randomness.
  95. */
  96. const size_t nonce_len = 8;
  97. mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
  98. size_t ciphertext_len = 0;
  99. /* Go for a conservative 16-byte (128-bit) tag
  100. * and append it to the ciphertext */
  101. const size_t tag_len = 16;
  102. ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
  103. (const unsigned char *) metadata, sizeof metadata,
  104. (const unsigned char *) message, sizeof message,
  105. ciphertext + nonce_len, &ciphertext_len,
  106. ciphertext + nonce_len + sizeof message, tag_len );
  107. if (ret != 0) {
  108. printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
  109. return 1;
  110. }
  111. ciphertext_len += nonce_len + tag_len;
  112. /*
  113. * The following information should now be transmitted:
  114. * - first ciphertext_len bytes of ciphertext buffer
  115. * - metadata if not already transmitted elsewhere
  116. */
  117. print_hex("ciphertext", ciphertext, ciphertext_len);
  118. /*
  119. * Decrypt-authenticate
  120. */
  121. unsigned char decrypted[128] = { 0 };
  122. size_t decrypted_len = 0;
  123. ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
  124. if (ret != 0) {
  125. printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
  126. return 1;
  127. }
  128. ret = mbedtls_cipher_auth_decrypt(&ctx,
  129. ciphertext, nonce_len,
  130. (const unsigned char *) metadata, sizeof metadata,
  131. ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
  132. decrypted, &decrypted_len,
  133. ciphertext + ciphertext_len - tag_len, tag_len );
  134. /* Checking the return code is CRITICAL for security here */
  135. if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
  136. printf("Something bad is happening! Data is not authentic!\r\n");
  137. return 1;
  138. }
  139. if (ret != 0) {
  140. printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
  141. return 1;
  142. }
  143. print_hex("decrypted", decrypted, decrypted_len);
  144. printf("\r\nDONE\r\n");
  145. return 0;
  146. }
  147. #if defined(TARGET_LIKE_MBED)
  148. #include "mbed-drivers/test_env.h"
  149. #include "minar/minar.h"
  150. static void run() {
  151. MBED_HOSTTEST_TIMEOUT(10);
  152. MBED_HOSTTEST_SELECT(default);
  153. MBED_HOSTTEST_DESCRIPTION(mbed TLS example authcrypt);
  154. MBED_HOSTTEST_START("MBEDTLS_EX_AUTHCRYPT");
  155. MBED_HOSTTEST_RESULT(example() == 0);
  156. }
  157. void app_start(int, char*[]) {
  158. /* Use 115200 bps for consistency with other examples */
  159. get_stdio_serial().baud(115200);
  160. minar::Scheduler::postCallback(mbed::util::FunctionPointer0<void>(run).bind());
  161. }
  162. #else
  163. int main() {
  164. return example();
  165. }
  166. #endif