Add comments to AEAD (non-PSA) examples

Signed-off-by: Manuel Pégourié-Gonnard <manuel.pegourie-gonnard@arm.com>
diff --git a/programs/psa/aead_non_psa.c b/programs/psa/aead_non_psa.c
index 4b48b3a..00c7f0e 100644
--- a/programs/psa/aead_non_psa.c
+++ b/programs/psa/aead_non_psa.c
@@ -1,8 +1,29 @@
-/*
- * This is a companion to aead_psa.c, doing the same operations with the
- * legacy Cipher API. The goal is that comparing the two programs will help people
- * migrating to the PSA Crypto API.
+/**
+ * Cipher API multi-part AEAD demonstration.
  *
+ * This program AEAD-encrypts a message, using the algorithm and key size
+ * specified on the command line, using the multi-part API.
+ *
+ * It comes with a companion program aead_psa.c, which does the same
+ * operations with the PSA Crypto API. The goal is that comparing the two
+ * programs will help people migrating to the PSA Crypto API.
+ *
+ * When used with multi-part AEAD operations, the `mbedtls_cipher_context`
+ * serves a triple purpose (1) hold the key, (2) store the algorithm when no
+ * operation is active, and (3) save progress information for the current
+ * operation. With PSA those roles are held by disinct objects: (1) a
+ * psa_key_id_t to hold the key, a (2) psa_algorithm_t to represent the
+ * algorithm, and (3) a psa_operation_t for multi-part progress.
+ *
+ * On the other hand, with PSA, the algorithms encodes the desired tag length;
+ * with Cipher the desired tag length needs to be tracked separately.
+ *
+ * This program and its companion aead_psa.c illustrate this by doing the
+ * same sequence of multi-part AEAD computation with both APIs; looking at the
+ * two side by side should make the differences and similarities clear.
+ */
+
+/*
  *  Copyright The Mbed TLS Contributors
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -19,26 +40,18 @@
  *  limitations under the License.
  */
 
-/*
- * When used with multi-part AEAD operations, the `mbedtls_cipher_context`
- * serves a triple purpose (1) hold the key, (2) store the algorithm when no
- * operation is active, and (3) save progress information for the current
- * operation. With PSA those roles are held by disinct objects: (1) a
- * psa_key_id_t to hold the key, a (2) psa_algorithm_t to represent the
- * algorithm, and (3) a psa_operation_t for multi-part progress.
- *
- * On the other hand, with PSA, the algorithms encodes the desired tag length;
- * with Cipher the desired tag length needs to be tracked separately.
- *
- * This program and its compation aead_psa.c illustrate this by doing the
- * same sequence of multi-part AEAD computation with both APIs; looking at the
- * two side by side should make the differences and similarities clear.
- */
-
-#include <stdio.h>
-
+/* First include Mbed TLS headers to get the Mbed TLS configuration and
+ * platform definitions that we'll use in this program. Also include
+ * standard C headers for functions we'll use here. */
 #include "mbedtls/build_info.h"
 
+#include "mbedtls/cipher.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+/* If the build options we need are not enabled, compile a placeholder. */
 #if !defined(MBEDTLS_CIPHER_C) || \
     !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_GCM_C) || \
     !defined(MBEDTLS_CHACHAPOLY_C)
@@ -51,52 +64,67 @@
 }
 #else
 
-#include <string.h>
+/* The real program starts here. */
 
-#include "mbedtls/cipher.h"
+const char usage[] = "Usage: aead_psa [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
 
-/*
- * Dummy data and helper functions
- */
-const char usage[] = "Usage: aead_non_psa [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
-
+/* Dummy data for encryption: IV/nonce, additional data, 2-part message */
 const unsigned char iv1[12] = { 0x00 };
 const unsigned char add_data1[] = { 0x01, 0x02 };
 const unsigned char msg1_part1[] = { 0x03, 0x04 };
 const unsigned char msg1_part2[] = { 0x05, 0x06, 0x07 };
 
+/* Dummy data (2nd message) */
 const unsigned char iv2[12] = { 0x10 };
 const unsigned char add_data2[] = { 0x11, 0x12 };
 const unsigned char msg2_part1[] = { 0x13, 0x14 };
 const unsigned char msg2_part2[] = { 0x15, 0x16, 0x17 };
 
+/* This must at least the sum of the length of the 2 parts for each message.
+ * This is a macro for the sake of compilers with insufficient C99 support. */
 #define MSG_MAX_SIZE 5
 
+/* Dummy key material - never do this in production!
+ * 32-byte is enough to all the key size supported by this program. */
 const unsigned char key_bytes[32] = { 0x2a };
 
-void print_out( const char *title, unsigned char *out, size_t len )
+/* Print the contents of a buffer in hex */
+void print_buf( const char *title, unsigned char *buf, size_t len )
 {
     printf( "%s:", title );
     for( size_t i = 0; i < len; i++ )
-        printf( " %02x", out[i] );
+        printf( " %02x", buf[i] );
     printf( "\n" );
 }
 
-#define CHK( code )         \
-    do {                    \
-        ret = code;         \
-        if( ret != 0 ) {    \
-            printf( "%03d: ret = -0x%04x\n", __LINE__, (unsigned) -ret ); \
-            goto exit;      \
-        }                   \
+/* Run an Mbed TLS function and bail out if it fails. */
+#define CHK( expr )                                             \
+    do                                                          \
+    {                                                           \
+        ret = ( expr );                                         \
+        if( ret != 0 )                                          \
+        {                                                       \
+            printf( "Error %d at line %d: %s\n",                \
+                    ret,                                        \
+                    __LINE__,                                   \
+                    #expr );                                    \
+            goto exit;                                          \
+        }                                                       \
     } while( 0 )
 
+/*
+ * Prepare encryption material:
+ * - interpret command-line argument
+ * - set up key
+ * - outputs: context and tag length, which together hold all the information
+ */
 static int aead_prepare( const char *info,
                            mbedtls_cipher_context_t *ctx,
                            size_t *tag_len )
 {
     int ret;
 
+    /* Convert arg to type + tag_len */
     mbedtls_cipher_type_t type;
     if( strcmp( info, "aes128-gcm" ) == 0 ) {
         type = MBEDTLS_CIPHER_AES_128_GCM;
@@ -115,9 +143,11 @@
         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
     }
 
+    /* Prepare context for the given type */
     CHK( mbedtls_cipher_setup( ctx,
                                mbedtls_cipher_info_from_type( type ) ) );
 
+    /* Import key */
     int key_len = mbedtls_cipher_get_key_bitlen( ctx );
     CHK( mbedtls_cipher_setkey( ctx, key_bytes, key_len, MBEDTLS_ENCRYPT ) );
 
@@ -125,9 +155,15 @@
     return( ret );
 }
 
+/*
+ * Print out some information.
+ *
+ * All of this information was present in the command line argument, but his
+ * function demonstrates how each piece can be recovered from (ctx, tag_len).
+ */
 static void aead_info( const mbedtls_cipher_context_t *ctx, size_t tag_len )
 {
-    // no convenient way to get the cipher type (for example, AES)
+    // no convenient way to get the just cipher type (for example, AES)
     const char *ciph = "???";
     int key_bits = mbedtls_cipher_get_key_bitlen( ctx );
     mbedtls_cipher_mode_t mode = mbedtls_cipher_get_cipher_mode( ctx );
@@ -139,6 +175,9 @@
     printf( "cipher: %s, %d, %s, %u\n", ciph, key_bits, mode_str, (unsigned) tag_len );
 }
 
+/*
+ * Encrypt a 2-part message.
+ */
 static int 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,
@@ -163,12 +202,15 @@
     p += tag_len;
 
     olen = p - out;
-    print_out( "cipher", out, olen );
+    print_buf( "cipher", out, olen );
 
 exit:
     return( ret );
 }
 
+/*
+ * AEAD demo: set up key/alg, print out info, encrypt messages.
+ */
 static int aead_demo( const char *info )
 {
     int ret = 0;
@@ -203,13 +245,20 @@
  */
 int main( int argc, char **argv )
 {
+    /* Check usage */
     if( argc != 2 )
     {
         puts( usage );
         return( 1 );
     }
 
-    aead_demo( argv[1] );
+    int ret;
+
+    /* Run the demo */
+    CHK( aead_demo( argv[1] ) );
+
+exit:
+    return( ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE );
 }
 
 #endif
diff --git a/programs/psa/aead_psa.c b/programs/psa/aead_psa.c
index 5ed32a5..2f0663d 100644
--- a/programs/psa/aead_psa.c
+++ b/programs/psa/aead_psa.c
@@ -1,9 +1,29 @@
-/*
- * This is a simple example of multi-part AEAD computation using the PSA
- * Crypto API. It comes with a companion program aead_non_psa.c, which does
- * the same operations with the legacy Cipher API. The goal is that comparing the
- * two programs will help people migrating to the PSA Crypto API.
+/**
+ * PSA API multi-part AEAD demonstration.
  *
+ * This program AEAD-encrypts a message, using the algorithm and key size
+ * specified on the command line, using the multi-part API.
+ *
+ * It comes with a companion program aead_non_psa.c, which does the same
+ * operations with the legacy Cipher API. The goal is that comparing the two
+ * programs will help people migrating to the PSA Crypto API.
+ *
+ * When used with multi-part AEAD operations, the `mbedtls_cipher_context`
+ * serves a triple purpose (1) hold the key, (2) store the algorithm when no
+ * operation is active, and (3) save progress information for the current
+ * operation. With PSA those roles are held by disinct objects: (1) a
+ * psa_key_id_t to hold the key, a (2) psa_algorithm_t to represent the
+ * algorithm, and (3) a psa_operation_t for multi-part progress.
+ *
+ * On the other hand, with PSA, the algorithms encodes the desired tag length;
+ * with Cipher the desired tag length needs to be tracked separately.
+ *
+ * This program and its companion aead_non_psa.c illustrate this by doing the
+ * same sequence of multi-part AEAD computation with both APIs; looking at the
+ * two side by side should make the differences and similarities clear.
+ */
+
+/*
  *  Copyright The Mbed TLS Contributors
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -20,26 +40,18 @@
  *  limitations under the License.
  */
 
-/*
- * When used with multi-part AEAD operations, the `mbedtls_cipher_context`
- * serves a triple purpose (1) hold the key, (2) store the algorithm when no
- * operation is active, and (3) save progress information for the current
- * operation. With PSA those roles are held by disinct objects: (1) a
- * psa_key_id_t to hold the key, a (2) psa_algorithm_t to represent the
- * algorithm, and (3) a psa_operation_t for multi-part progress.
- *
- * On the other hand, with PSA, the algorithms encodes the desired tag length;
- * with Cipher the desired tag length needs to be tracked separately.
- *
- * This program and its compation aead_non_psa.c illustrate this by doing the
- * same sequence of multi-part AEAD computation with both APIs; looking at the
- * two side by side should make the differences and similarities clear.
- */
-
-#include <stdio.h>
-
+/* First include Mbed TLS headers to get the Mbed TLS configuration and
+ * platform definitions that we'll use in this program. Also include
+ * standard C headers for functions we'll use here. */
 #include "mbedtls/build_info.h"
 
+#include "psa/crypto.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+/* If the build options we need are not enabled, compile a placeholder. */
 #if !defined(MBEDTLS_PSA_CRYPTO_C) || \
     !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_GCM_C) || \
     !defined(MBEDTLS_CHACHAPOLY_C) || \
@@ -54,52 +66,68 @@
 }
 #else
 
-#include <string.h>
+/* The real program starts here. */
 
-#include "psa/crypto.h"
-
-/*
- * Dummy data and helper functions
- */
 const char usage[] = "Usage: aead_psa [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
 
+/* Dummy data for encryption: IV/nonce, additional data, 2-part message */
 const unsigned char iv1[12] = { 0x00 };
 const unsigned char add_data1[] = { 0x01, 0x02 };
 const unsigned char msg1_part1[] = { 0x03, 0x04 };
 const unsigned char msg1_part2[] = { 0x05, 0x06, 0x07 };
 
+/* Dummy data (2nd message) */
 const unsigned char iv2[12] = { 0x10 };
 const unsigned char add_data2[] = { 0x11, 0x12 };
 const unsigned char msg2_part1[] = { 0x13, 0x14 };
 const unsigned char msg2_part2[] = { 0x15, 0x16, 0x17 };
 
+/* This must at least the sum of the length of the 2 parts for each message.
+ * This is a macro for the sake of compilers with insufficient C99 support. */
 #define MSG_MAX_SIZE 5
 
+/* Dummy key material - never do this in production!
+ * 32-byte is enough to all the key size supported by this program. */
 const unsigned char key_bytes[32] = { 0x2a };
 
-void print_out( const char *title, unsigned char *out, size_t len )
+/* Print the contents of a buffer in hex */
+void print_buf( const char *title, uint8_t *buf, size_t len )
 {
     printf( "%s:", title );
     for( size_t i = 0; i < len; i++ )
-        printf( " %02x", out[i] );
+        printf( " %02x", buf[i] );
     printf( "\n" );
 }
 
-#define CHK( code )     \
-    do {                \
-        status = code;     \
-        if( status != PSA_SUCCESS ) { \
-            printf( "%03d: status = %d\n", __LINE__, status ); \
-            goto exit;  \
-        } \
-    } while( 0 )
+/* Run a PSA function and bail out if it fails. */
+#define PSA_CHECK( expr )                                       \
+    do                                                          \
+    {                                                           \
+        status = ( expr );                                      \
+        if( status != PSA_SUCCESS )                             \
+        {                                                       \
+            printf( "Error %d at line %d: %s\n",                \
+                    (int) status,                               \
+                    __LINE__,                                   \
+                    #expr );                                    \
+            goto exit;                                          \
+        }                                                       \
+    }                                                           \
+    while( 0 )
 
+/*
+ * Prepare encryption material:
+ * - interpret command-line argument
+ * - set up key
+ * - outputs: key and algorithm, which together hold all the information
+ */
 static psa_status_t aead_prepare( const char *info,
                                   psa_key_id_t *key,
                                   psa_algorithm_t *alg )
 {
     psa_status_t status;
 
+    /* Convert arg to alg + key_bits + key_type */
     size_t key_bits;
     psa_key_type_t key_type;
     if( strcmp( info, "aes128-gcm" ) == 0 ) {
@@ -123,18 +151,26 @@
         return( PSA_ERROR_INVALID_ARGUMENT );
     }
 
+    /* Prepare key attibutes */
     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
     psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_ENCRYPT );
     psa_set_key_algorithm( &attributes, *alg );
     psa_set_key_type( &attributes, key_type );
-    psa_set_key_bits( &attributes, key_bits );
+    psa_set_key_bits( &attributes, key_bits ); // optional
 
-    CHK( psa_import_key( &attributes, key_bytes, key_bits / 8, key ) );
+    /* Import key */
+    PSA_CHECK( psa_import_key( &attributes, key_bytes, key_bits / 8, key ) );
 
 exit:
     return( status );
 }
 
+/*
+ * Print out some information.
+ *
+ * All of this information was present in the command line argument, but his
+ * function demonstrates how each piece can be recovered from (key, alg).
+ */
 static void aead_info( psa_key_id_t key, psa_algorithm_t alg )
 {
     psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
@@ -155,6 +191,9 @@
             type_str, (unsigned) key_bits, base_str, (unsigned) tag_len );
 }
 
+/*
+ * Encrypt a 2-part message.
+ */
 static int aead_encrypt( psa_key_id_t key, psa_algorithm_t alg,
         const unsigned char *iv, size_t iv_len,
         const unsigned char *ad, size_t ad_len,
@@ -168,29 +207,31 @@
     unsigned char tag[PSA_AEAD_TAG_MAX_SIZE];
 
     psa_aead_operation_t op = PSA_AEAD_OPERATION_INIT;
-    CHK( psa_aead_encrypt_setup( &op, key, alg ) );
+    PSA_CHECK( psa_aead_encrypt_setup( &op, key, alg ) );
 
-    CHK( psa_aead_set_nonce( &op, iv, iv_len ) );
-    CHK( psa_aead_update_ad( &op, ad, ad_len ) );
-    CHK( psa_aead_update( &op, pa, pa_len, p, end - p, &olen ) );
+    PSA_CHECK( psa_aead_set_nonce( &op, iv, iv_len ) );
+    PSA_CHECK( psa_aead_update_ad( &op, ad, ad_len ) );
+    PSA_CHECK( psa_aead_update( &op, pa, pa_len, p, end - p, &olen ) );
     p += olen;
-    CHK( psa_aead_update( &op, pb, pb_len, p, end - p, &olen ) );
+    PSA_CHECK( psa_aead_update( &op, pb, pb_len, p, end - p, &olen ) );
     p += olen;
-    CHK( psa_aead_finish( &op, p, end - p, &olen,
+    PSA_CHECK( psa_aead_finish( &op, p, end - p, &olen,
                                tag, sizeof( tag ), &olen_tag ) );
     p += olen;
     memcpy( p, tag, olen_tag );
     p += olen_tag;
 
     olen = p - out;
-    print_out( "out", out, olen );
+    print_buf( "out", out, olen );
 
 exit:
-    /* required on errors, harmless on success */
-    psa_aead_abort( &op );
+    psa_aead_abort( &op ); // required on errors, harmless on success
     return( status );
 }
 
+/*
+ * AEAD demo: set up key/alg, print out info, encrypt messages.
+ */
 static psa_status_t aead_demo( const char *info )
 {
     psa_status_t status;
@@ -198,15 +239,15 @@
     psa_key_id_t key;
     psa_algorithm_t alg;
 
-    CHK( aead_prepare( info, &key, &alg ) );
+    PSA_CHECK( aead_prepare( info, &key, &alg ) );
 
     aead_info( key, alg );
 
-    CHK( aead_encrypt( key, alg,
+    PSA_CHECK( aead_encrypt( key, alg,
                        iv1, sizeof( iv1 ), add_data1, sizeof( add_data1 ),
                        msg1_part1, sizeof( msg1_part1 ),
                        msg1_part2, sizeof( msg1_part2 ) ) );
-    CHK( aead_encrypt( key, alg,
+    PSA_CHECK( aead_encrypt( key, alg,
                        iv2, sizeof( iv2 ), add_data2, sizeof( add_data2 ),
                        msg2_part1, sizeof( msg2_part1 ),
                        msg2_part2, sizeof( msg2_part2 ) ) );
@@ -222,17 +263,26 @@
  */
 int main( int argc, char **argv )
 {
+    psa_status_t status = PSA_SUCCESS;
+
+    /* Check usage */
     if( argc != 2 )
     {
         puts( usage );
-        return( 1 );
+        return( EXIT_FAILURE );
     }
 
-    psa_status_t status = psa_crypto_init();
-    if( status != PSA_SUCCESS )
-        printf( "psa init: %d\n", status );
+    /* Initialize the PSA crypto library. */
+    PSA_CHECK( psa_crypto_init( ) );
 
-    aead_demo( argv[1] );
+    /* Run the demo */
+    PSA_CHECK( aead_demo( argv[1] ) );
+
+    /* Deinitialize the PSA crypto library. */
+    mbedtls_psa_crypto_free( );
+
+exit:
+    return( status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE );
 }
 
 #endif