blob: 257a1adf1b14d2015aee5155127a007f1944dc9c [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 *
4 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
Manuel Pégourié-Gonnard37ff1402015-09-04 14:21:07 +02005 * 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.
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +020018 *
19 * This file is part of mbed TLS (https://tls.mbed.org)
20 */
21
22#include "mbedtls/cipher.h"
23#include "mbedtls/entropy.h"
24#include "mbedtls/ctr_drbg.h"
25
26#include <stdio.h>
27#include <string.h>
28
29static void print_hex(const char *title, const unsigned char buf[], size_t len)
30{
31 printf("%s: ", title);
32
33 for (size_t i = 0; i < len; i++)
34 printf("%02x", buf[i]);
35
36 printf("\r\n");
37}
38
39/*
40 * The pre-shared key. Should be generated randomly and be unique to the
41 * device/channel/etc. Just used a fixed on here for simplicity.
42 */
43static const unsigned char secret_key[16] = {
44 0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
45 0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
46};
47
48static int example(void)
49{
50 /* message that should be protected */
51 const char message[] = "Some things are better left unread";
52 /* metadata transmitted in the clear but authenticated */
53 const char metadata[] = "eg sequence number, routing info";
54 /* ciphertext buffer large enough to hold message + nonce + tag */
55 unsigned char ciphertext[128] = { 0 };
56 int ret;
57
58 printf("\r\n\r\n");
59 print_hex("plaintext message", (unsigned char *) message, sizeof message);
60
61 /*
62 * Setup random number generator
63 * (Note: later this might be done automatically.)
64 */
65 mbedtls_entropy_context entropy; /* entropy pool for seeding PRNG */
66 mbedtls_ctr_drbg_context drbg; /* pseudo-random generator */
67
68 mbedtls_entropy_init(&entropy);
69 mbedtls_ctr_drbg_init(&drbg);
70
71 /* Seed the PRNG using the entropy pool, and throw in our secret key as an
72 * additional source of randomness. */
73 ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
74 secret_key, sizeof (secret_key));
75 if (ret != 0) {
76 printf("mbedtls_ctr_drbg_init() returned -0x%04X\r\n", -ret);
77 return 1;
78 }
79
80 /*
81 * Setup AES-CCM contex
82 */
83 mbedtls_cipher_context_t ctx;
84
85 mbedtls_cipher_init(&ctx);
86
87 ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
88 if (ret != 0) {
89 printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
90 return 1;
91 }
92
93 ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
94 if (ret != 0) {
95 printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
96 return 1;
97 }
98
99 /*
100 * Encrypt-authenticate the message and authenticate additional data
101 *
102 * First generate a random 8-byte nonce.
103 * Put it directly in the output buffer as the recipient will need it.
104 *
105 * Warning: you must never re-use the same (key, nonce) pair. One of the
106 * best ways to ensure this to use a counter for the nonce. However this
107 * means you should save the counter accross rebots, if the key is a
108 * long-term one. The alternative we choose here is to generate the nonce
109 * randomly. However it only works if you have a good source of
110 * randomness.
111 */
112 const size_t nonce_len = 8;
113 mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
114
115 size_t ciphertext_len = 0;
116 /* Go for a conservative 16-byte (128-bit) tag
117 * and append it to the ciphertext */
118 const size_t tag_len = 16;
119 ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
120 (const unsigned char *) metadata, sizeof metadata,
121 (const unsigned char *) message, sizeof message,
122 ciphertext + nonce_len, &ciphertext_len,
123 ciphertext + nonce_len + sizeof message, tag_len );
124 if (ret != 0) {
125 printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
126 return 1;
127 }
128 ciphertext_len += nonce_len + tag_len;
129
130 /*
131 * The following information should now be transmitted:
132 * - first ciphertext_len bytes of ciphertext buffer
133 * - metadata if not already transmitted elsewhere
134 */
135 print_hex("ciphertext", ciphertext, ciphertext_len);
136
137 /*
138 * Decrypt-authenticate
139 */
140 unsigned char decrypted[128] = { 0 };
141 size_t decrypted_len = 0;
142
143 ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
144 if (ret != 0) {
145 printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
146 return 1;
147 }
148
149 ret = mbedtls_cipher_auth_decrypt(&ctx,
150 ciphertext, nonce_len,
151 (const unsigned char *) metadata, sizeof metadata,
152 ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
153 decrypted, &decrypted_len,
154 ciphertext + ciphertext_len - tag_len, tag_len );
155 /* Checking the return code is CRITICAL for security here */
156 if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
157 printf("Something bad is happening! Data is not authentic!\r\n");
158 return 1;
159 }
160 if (ret != 0) {
161 printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
162 return 1;
163 }
164
165 print_hex("decrypted", decrypted, decrypted_len);
166
167 printf("\r\nDONE\r\n");
168
169 return 0;
170}
171
172#if defined(TARGET_LIKE_MBED)
173
174#include "mbed/test_env.h"
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200175#include "minar/minar.h"
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200176
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200177static void run() {
Manuel Pégourié-Gonnardbd5bbec2015-08-06 18:10:17 +0200178 /* Use 115200 bps for consistency with other examples */
179 Serial pc(USBTX, USBRX);
180 pc.baud(115200);
181
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200182 MBED_HOSTTEST_TIMEOUT(10);
183 MBED_HOSTTEST_SELECT(default);
184 MBED_HOSTTEST_DESCRIPTION(mbed TLS example authcrypt);
185 MBED_HOSTTEST_START("MBEDTLS_EX_AUTHCRYPT");
186 MBED_HOSTTEST_RESULT(example() == 0);
187}
188
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200189void app_start(int, char*[]) {
Manuel Pégourié-Gonnardca4fb712015-09-18 14:36:57 +0200190 minar::Scheduler::postCallback(mbed::util::FunctionPointer0<void>(run).bind());
Manuel Pégourié-Gonnarde87b04c2015-08-11 04:09:44 +0200191}
192
Manuel Pégourié-Gonnard63e7eba2015-07-28 14:17:48 +0200193#else
194
195int main() {
196 return example();
197}
198
199#endif