blob: 001a8090600d56dd482e4936776937141ae121ba [file] [log] [blame]
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +02001/*
2 * Hello world example of using the authenticated encryption with mbed TLS
3 *
Bence Szépkúti44bfbe32020-08-19 16:54:51 +02004 * Copyright The Mbed TLS Contributors
Bence Szépkúti4e9f7122020-06-05 13:02:18 +02005 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 *
7 * This file is provided under the Apache License 2.0, or the
8 * GNU General Public License v2.0 or later.
9 *
10 * **********
11 * Apache License 2.0:
Manuel Pégourié-Gonnard37ff1402015-09-04 14:21:07 +020012 *
13 * Licensed under the Apache License, Version 2.0 (the "License"); you may
14 * not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
21 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +020024 *
Bence Szépkúti4e9f7122020-06-05 13:02:18 +020025 * **********
26 *
27 * **********
28 * GNU General Public License v2.0 or later:
29 *
30 * This program is free software; you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation; either version 2 of the License, or
33 * (at your option) any later version.
34 *
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
39 *
40 * You should have received a copy of the GNU General Public License along
41 * with this program; if not, write to the Free Software Foundation, Inc.,
42 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
43 *
44 * **********
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +020045 */
46
47#include "mbedtls/cipher.h"
48#include "mbedtls/entropy.h"
49#include "mbedtls/ctr_drbg.h"
50
51#include <stdio.h>
52#include <string.h>
53
54static void print_hex(const char *title, const unsigned char buf[], size_t len)
55{
56 printf("%s: ", title);
57
58 for (size_t i = 0; i < len; i++)
59 printf("%02x", buf[i]);
60
61 printf("\r\n");
62}
63
64/*
65 * The pre-shared key. Should be generated randomly and be unique to the
66 * device/channel/etc. Just used a fixed on here for simplicity.
67 */
68static const unsigned char secret_key[16] = {
69 0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
70 0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
71};
72
73static int example(void)
74{
75 /* message that should be protected */
76 const char message[] = "Some things are better left unread";
77 /* metadata transmitted in the clear but authenticated */
78 const char metadata[] = "eg sequence number, routing info";
79 /* ciphertext buffer large enough to hold message + nonce + tag */
80 unsigned char ciphertext[128] = { 0 };
81 int ret;
82
83 printf("\r\n\r\n");
84 print_hex("plaintext message", (unsigned char *) message, sizeof message);
85
86 /*
87 * Setup random number generator
88 * (Note: later this might be done automatically.)
89 */
90 mbedtls_entropy_context entropy; /* entropy pool for seeding PRNG */
91 mbedtls_ctr_drbg_context drbg; /* pseudo-random generator */
92
93 mbedtls_entropy_init(&entropy);
94 mbedtls_ctr_drbg_init(&drbg);
95
96 /* Seed the PRNG using the entropy pool, and throw in our secret key as an
97 * additional source of randomness. */
98 ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
99 secret_key, sizeof (secret_key));
100 if (ret != 0) {
101 printf("mbedtls_ctr_drbg_init() returned -0x%04X\r\n", -ret);
102 return 1;
103 }
104
105 /*
106 * Setup AES-CCM contex
107 */
108 mbedtls_cipher_context_t ctx;
109
110 mbedtls_cipher_init(&ctx);
111
112 ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
113 if (ret != 0) {
114 printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
115 return 1;
116 }
117
118 ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
119 if (ret != 0) {
120 printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
121 return 1;
122 }
123
124 /*
125 * Encrypt-authenticate the message and authenticate additional data
126 *
127 * First generate a random 8-byte nonce.
128 * Put it directly in the output buffer as the recipient will need it.
129 *
130 * Warning: you must never re-use the same (key, nonce) pair. One of the
131 * best ways to ensure this to use a counter for the nonce. However this
132 * means you should save the counter accross rebots, if the key is a
133 * long-term one. The alternative we choose here is to generate the nonce
134 * randomly. However it only works if you have a good source of
135 * randomness.
136 */
137 const size_t nonce_len = 8;
138 mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
139
140 size_t ciphertext_len = 0;
141 /* Go for a conservative 16-byte (128-bit) tag
142 * and append it to the ciphertext */
143 const size_t tag_len = 16;
144 ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
145 (const unsigned char *) metadata, sizeof metadata,
146 (const unsigned char *) message, sizeof message,
147 ciphertext + nonce_len, &ciphertext_len,
148 ciphertext + nonce_len + sizeof message, tag_len );
149 if (ret != 0) {
150 printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
151 return 1;
152 }
153 ciphertext_len += nonce_len + tag_len;
154
155 /*
156 * The following information should now be transmitted:
157 * - first ciphertext_len bytes of ciphertext buffer
158 * - metadata if not already transmitted elsewhere
159 */
160 print_hex("ciphertext", ciphertext, ciphertext_len);
161
162 /*
163 * Decrypt-authenticate
164 */
165 unsigned char decrypted[128] = { 0 };
166 size_t decrypted_len = 0;
167
168 ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
169 if (ret != 0) {
170 printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
171 return 1;
172 }
173
174 ret = mbedtls_cipher_auth_decrypt(&ctx,
175 ciphertext, nonce_len,
176 (const unsigned char *) metadata, sizeof metadata,
177 ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
178 decrypted, &decrypted_len,
179 ciphertext + ciphertext_len - tag_len, tag_len );
180 /* Checking the return code is CRITICAL for security here */
181 if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
182 printf("Something bad is happening! Data is not authentic!\r\n");
183 return 1;
184 }
185 if (ret != 0) {
186 printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
187 return 1;
188 }
189
190 print_hex("decrypted", decrypted, decrypted_len);
191
192 printf("\r\nDONE\r\n");
193
194 return 0;
195}
196
197#if defined(TARGET_LIKE_MBED)
198
Manuel Pégourié-Gonnard71956c92015-10-21 17:59:05 +0200199#include "mbed-drivers/test_env.h"
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200200#include "minar/minar.h"
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200201
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200202static void run() {
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200203 MBED_HOSTTEST_TIMEOUT(10);
204 MBED_HOSTTEST_SELECT(default);
205 MBED_HOSTTEST_DESCRIPTION(mbed TLS example authcrypt);
206 MBED_HOSTTEST_START("MBEDTLS_EX_AUTHCRYPT");
207 MBED_HOSTTEST_RESULT(example() == 0);
208}
209
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200210void app_start(int, char*[]) {
Janos Follath60ddf162016-03-17 13:55:07 +0000211 /* Use 115200 bps for consistency with other examples */
212 get_stdio_serial().baud(115200);
Manuel Pégourié-Gonnardca4fb712015-09-18 14:36:57 +0200213 minar::Scheduler::postCallback(mbed::util::FunctionPointer0<void>(run).bind());
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200214}
215
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200216#else
217
218int main() {
219 return example();
220}
221
222#endif