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