Hello world example of using the authenticated encryption with mbed TLS. The canonical source for this example lives at https://github.com/ARMmbed/mbed-os-example-tls

mbed TLS Benchmark example on mbed OS

This application performs authenticated encryption and authenticated decryption of a buffer. It serves as a tutorial for the basic authenticated encryption functions of mbed TLS.

Getting started

Building with mbed CLI

If you'd like to use mbed CLI to build this, then you should set up your environment if you have not done so already. For instructions, refer to the main readme. The instructions on this page relate to using the developer.mbed.org Online Compiler

Import the program in to the Online Compiler, select your board from the drop down in the top right hand corner and then compile the application. Once it has built, you can drag and drop the binary onto your device.

Monitoring the application

The output in the terminal window should be similar to this:

terminal output

plaintext message: 536f6d65207468696e67732061726520626574746572206c65667420756e7265616400
ciphertext: c57f7afb94f14c7977d785d08682a2596bd62ee9dcf216b8cccd997afee9b402f5de1739e8e6467aa363749ef39392e5c66622b01c7203ec0a3d14
decrypted: 536f6d65207468696e67732061726520626574746572206c65667420756e7265616400

DONE

Files at this revision

API Documentation at this revision

Comitter:
mbed_official
Date:
Fri Jul 14 15:45:04 2017 +0100
Parent:
35:e7af1b5a1bcc
Child:
37:971586eea0f6
Commit message:
Merge pull request #95 from andresag01/refactor-authcrypt

Refactor authcrypt example
.
Commit copied from https://github.com/ARMmbed/mbed-os-example-tls

Changed in this revision

authcrypt.cpp Show annotated file Show diff for this revision Revisions of this file
authcrypt.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/authcrypt.cpp	Fri Jul 14 15:45:04 2017 +0100
@@ -0,0 +1,185 @@
+/*
+ *  Hello world example of using the authenticated encryption with mbed TLS
+ *
+ *  Copyright (C) 2017, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include "authcrypt.h"
+
+#include "mbed.h"
+
+#include "mbedtls/cipher.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+#if DEBUG_LEVEL > 0
+#include "mbedtls/debug.h"
+#endif
+
+#include "mbedtls/platform.h"
+
+#include <string.h>
+
+const unsigned char Authcrypt::secret_key[16] = {
+    0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
+    0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
+};
+
+const char Authcrypt::message[] = "Some things are better left unread";
+
+const char Authcrypt::metadata[] = "eg sequence number, routing info";
+
+Authcrypt::Authcrypt()
+{
+    memset(ciphertext, 0, sizeof(ciphertext));
+    memset(decrypted, 0, sizeof(decrypted));
+
+    mbedtls_entropy_init(&entropy);
+    mbedtls_ctr_drbg_init(&drbg);
+    mbedtls_cipher_init(&cipher);
+}
+
+Authcrypt::~Authcrypt()
+{
+    memset(ciphertext, 0, sizeof(ciphertext));
+    memset(decrypted, 0, sizeof(decrypted));
+
+    mbedtls_cipher_free(&cipher);
+    mbedtls_ctr_drbg_free(&drbg);
+    mbedtls_entropy_free(&entropy);
+}
+
+int Authcrypt::run()
+{
+    mbedtls_printf("\r\n\r\n");
+    print_hex("plaintext message",
+              reinterpret_cast<const unsigned char *>(message),
+              sizeof(message));
+
+    /*
+     * Seed the PRNG using the entropy pool, and throw in our secret key as an
+     * additional source of randomness.
+     */
+    int ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
+                                    secret_key, sizeof(secret_key));
+    if (ret != 0) {
+        mbedtls_printf("mbedtls_ctr_drbg_seed() returned -0x%04X\r\n", -ret);
+        return ret;
+    }
+
+    /* Setup AES-CCM contex */
+    ret = mbedtls_cipher_setup(&cipher,
+                    mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
+    if (ret != 0) {
+        mbedtls_printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
+        return ret;
+    }
+
+    ret = mbedtls_cipher_setkey(&cipher, secret_key,
+                                8 * sizeof(secret_key), MBEDTLS_ENCRYPT);
+    if (ret != 0) {
+        mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
+        return ret;
+    }
+
+    /*
+     * Encrypt-authenticate the message and authenticate additional data
+     *
+     * First generate a random 8-byte nonce.
+     * Put it directly in the output buffer as the recipient will need it.
+     *
+     * Warning: you must never re-use the same (key, nonce) pair. One of
+     * the best ways to ensure this to use a counter for the nonce.
+     * However, this means you should save the counter accross rebots, if
+     * the key is a long-term one. The alternative we choose here is to
+     * generate the nonce randomly. However it only works if you have a
+     * good source of randomness.
+     */
+    const size_t nonce_len = 8;
+    mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
+
+    size_t ciphertext_len = 0;
+    /*
+     * Go for a conservative 16-byte (128-bit) tag and append it to the
+     * ciphertext
+     */
+    const size_t tag_len = 16;
+    ret = mbedtls_cipher_auth_encrypt(&cipher, ciphertext, nonce_len,
+                        reinterpret_cast<const unsigned char *>(metadata),
+                        sizeof(metadata),
+                        reinterpret_cast<const unsigned char *>(message),
+                        sizeof(message),
+                        ciphertext + nonce_len, &ciphertext_len,
+                        ciphertext + nonce_len + sizeof(message),
+                        tag_len);
+    if (ret != 0) {
+        mbedtls_printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n",
+                       -ret);
+        return ret;
+    }
+    ciphertext_len += nonce_len + tag_len;
+
+    /*
+     * The following information should now be transmitted:
+     * - First ciphertext_len bytes of ciphertext buffer
+     * - Metadata if not already transmitted elsewhere
+     */
+    print_hex("ciphertext", ciphertext, ciphertext_len);
+
+    /* Decrypt-authenticate */
+    size_t decrypted_len = 0;
+
+    ret = mbedtls_cipher_setkey(&cipher, secret_key, 8 * sizeof(secret_key),
+                                MBEDTLS_DECRYPT);
+    if (ret != 0) {
+        mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
+        return ret;
+    }
+
+    ret = mbedtls_cipher_auth_decrypt(&cipher, ciphertext, nonce_len,
+                    reinterpret_cast<const unsigned char *>(metadata),
+                    sizeof(metadata), ciphertext + nonce_len,
+                    ciphertext_len - nonce_len - tag_len, decrypted,
+                    &decrypted_len, ciphertext + ciphertext_len - tag_len,
+                    tag_len);
+    /* Checking the return code is CRITICAL for security here */
+    if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
+        mbedtls_printf("Something bad is happening! Data is not "
+                       "authentic!\r\n");
+        return ret;
+    } else if (ret != 0) {
+        mbedtls_printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n",
+                       -ret);
+        return ret;
+    }
+
+    print_hex("decrypted", decrypted, decrypted_len);
+
+    mbedtls_printf("\r\nDONE\r\n");
+
+    return 0;
+}
+
+void Authcrypt::print_hex(const char *title,
+                          const unsigned char buf[],
+                          size_t len)
+{
+    mbedtls_printf("%s: ", title);
+
+    for (size_t i = 0; i < len; i++)
+        mbedtls_printf("%02x", buf[i]);
+
+    mbedtls_printf("\r\n");
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/authcrypt.h	Fri Jul 14 15:45:04 2017 +0100
@@ -0,0 +1,108 @@
+/*
+ *  Hello world example of using the authenticated encryption with mbed TLS
+ *
+ *  Copyright (C) 2017, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#ifndef _AUTHCRYPT_H_
+#define _AUTHCRYPT_H_
+
+#include "mbedtls/cipher.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+
+/**
+ * This class implements the logic to demonstrate authenticated encryption using
+ * mbed TLS.
+ */
+class Authcrypt
+{
+public:
+    /**
+     * Construct an Authcrypt instance
+     */
+    Authcrypt();
+
+    /**
+     * Free any allocated resources
+     */
+    ~Authcrypt();
+
+    /**
+     * Run the authenticated encryption example
+     *
+     * \return  0 if successful
+     */
+    int run();
+
+private:
+    /**
+     * Print a buffer's contents in hexadecimal
+     *
+     * \param[in]   title
+     *              The string to print before the hex string
+     * \param[in]   buf
+     *              The buffer to print in hex
+     * \param[in]   len
+     *              The length of the buffer
+     */
+    void print_hex(const char *title, const unsigned char buf[], size_t len);
+
+    /**
+     * The pre-shared key
+     *
+     * \note This should be generated randomly and be unique to the
+     *       device/channel/etc. Just used a fixed on here for simplicity.
+     */
+    static const unsigned char secret_key[16];
+
+    /**
+     * Message that should be protected
+     */
+    static const char message[];
+
+    /**
+     * Metadata transmitted in the clear but authenticated
+     */
+    static const char metadata[];
+
+    /**
+     * Ciphertext buffer large enough to hold message + nonce + tag
+     */
+    unsigned char ciphertext[128];
+
+    /**
+     * Plaintext buffer large enough to hold the decrypted message
+     */
+    unsigned char decrypted[128];
+
+    /**
+     * Entropy pool for seeding PRNG
+     */
+    mbedtls_entropy_context entropy;
+
+    /**
+     * Pseudo-random generator
+     */
+    mbedtls_ctr_drbg_context drbg;
+
+    /**
+     * The block cipher configuration
+     */
+    mbedtls_cipher_context_t cipher;
+};
+
+#endif /* _AUTHCRYPT_H_ */
--- a/main.cpp	Tue Jul 11 16:45:05 2017 +0100
+++ b/main.cpp	Fri Jul 14 15:45:04 2017 +0100
@@ -1,7 +1,7 @@
 /*
  *  Hello world example of using the authenticated encryption with mbed TLS
  *
- *  Copyright (C) 2016, ARM Limited, All Rights Reserved
+ *  Copyright (C) 2016-2017, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -19,166 +19,20 @@
 
 #include "mbed.h"
 
-#include "mbedtls/cipher.h"
-#include "mbedtls/entropy.h"
-#include "mbedtls/ctr_drbg.h"
-#if DEBUG_LEVEL > 0
-#include "mbedtls/debug.h"
-#endif
+#include "authcrypt.h"
 
 #include "mbedtls/platform.h"
 
-#include <string.h>
-
-#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
-#include "mbedtls/memory_buffer_alloc.h"
-#endif
-
-static void print_hex(const char *title, const unsigned char buf[], size_t len)
-{
-    mbedtls_printf("%s: ", title);
-
-    for (size_t i = 0; i < len; i++)
-        mbedtls_printf("%02x", buf[i]);
-
-    mbedtls_printf("\r\n");
-}
-
-/*
- * The pre-shared key. Should be generated randomly and be unique to the
- * device/channel/etc. Just used a fixed on here for simplicity.
- */
-static const unsigned char secret_key[16] = {
-    0xf4, 0x82, 0xc6, 0x70, 0x3c, 0xc7, 0x61, 0x0a,
-    0xb9, 0xa0, 0xb8, 0xe9, 0x87, 0xb8, 0xc1, 0x72,
-};
-
-static int example(void)
-{
-    /* message that should be protected */
-    const char message[] = "Some things are better left unread";
-    /* metadata transmitted in the clear but authenticated */
-    const char metadata[] = "eg sequence number, routing info";
-    /* ciphertext buffer large enough to hold message + nonce + tag */
-    unsigned char ciphertext[128] = { 0 };
-    int ret;
+int main() {
+    int exit_code = MBEDTLS_EXIT_SUCCESS;
+    Authcrypt *authcrypt = new Authcrypt();
 
-    mbedtls_printf("\r\n\r\n");
-    print_hex("plaintext message", (unsigned char *) message, sizeof message);
-
-    /*
-     * Setup random number generator
-     * (Note: later this might be done automatically.)
-     */
-    mbedtls_entropy_context entropy;    /* entropy pool for seeding PRNG */
-    mbedtls_ctr_drbg_context drbg;      /* pseudo-random generator */
-
-    mbedtls_entropy_init(&entropy);
-    mbedtls_ctr_drbg_init(&drbg);
-
-    /* Seed the PRNG using the entropy pool, and throw in our secret key as an
-     * additional source of randomness. */
-    ret = mbedtls_ctr_drbg_seed(&drbg, mbedtls_entropy_func, &entropy,
-                                       secret_key, sizeof secret_key);
-    if (ret != 0) {
-        return 1;
-    }
-
-    /*
-     * Setup AES-CCM contex
-     */
-    mbedtls_cipher_context_t ctx;
-
-    mbedtls_cipher_init(&ctx);
-
-    ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_CCM));
-    if (ret != 0) {
-        mbedtls_printf("mbedtls_cipher_setup() returned -0x%04X\r\n", -ret);
-        return 1;
-    }
-
-    ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_ENCRYPT);
-    if (ret != 0) {
-        mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
-        return 1;
+    if (authcrypt->run() != 0) {
+        exit_code = MBEDTLS_EXIT_FAILURE;
+        mbedtls_printf("\r\nFAIL\r\n");
     }
 
-    /*
-     * Encrypt-authenticate the message and authenticate additional data
-     *
-     * First generate a random 8-byte nonce.
-     * Put it directly in the output buffer as the recipient will need it.
-     *
-     * Warning: you must never re-use the same (key, nonce) pair. One of the
-     * best ways to ensure this to use a counter for the nonce. However this
-     * means you should save the counter accross rebots, if the key is a
-     * long-term one. The alternative we choose here is to generate the nonce
-     * randomly. However it only works if you have a good source of
-     * randomness.
-     */
-    const size_t nonce_len = 8;
-    mbedtls_ctr_drbg_random(&drbg, ciphertext, nonce_len);
-
-    size_t ciphertext_len = 0;
-    /* Go for a conservative 16-byte (128-bit) tag
-     * and append it to the ciphertext */
-    const size_t tag_len = 16;
-    ret = mbedtls_cipher_auth_encrypt(&ctx, ciphertext, nonce_len,
-                              (const unsigned char *) metadata, sizeof metadata,
-                              (const unsigned char *) message, sizeof message,
-                              ciphertext + nonce_len, &ciphertext_len,
-                              ciphertext + nonce_len + sizeof message, tag_len );
-    if (ret != 0) {
-        mbedtls_printf("mbedtls_cipher_auth_encrypt() returned -0x%04X\r\n", -ret);
-        return 1;
-    }
-    ciphertext_len += nonce_len + tag_len;
-
-    /*
-     * The following information should now be transmitted:
-     * - first ciphertext_len bytes of ciphertext buffer
-     * - metadata if not already transmitted elsewhere
-     */
-    print_hex("ciphertext", ciphertext, ciphertext_len);
+    delete authcrypt;
 
-    /*
-     * Decrypt-authenticate
-     */
-    unsigned char decrypted[128] = { 0 };
-    size_t decrypted_len = 0;
-
-    ret = mbedtls_cipher_setkey(&ctx, secret_key, 8 * sizeof secret_key, MBEDTLS_DECRYPT);
-    if (ret != 0) {
-        mbedtls_printf("mbedtls_cipher_setkey() returned -0x%04X\r\n", -ret);
-        return 1;
-    }
-
-    ret = mbedtls_cipher_auth_decrypt(&ctx,
-                              ciphertext, nonce_len,
-                              (const unsigned char *) metadata, sizeof metadata,
-                              ciphertext + nonce_len, ciphertext_len - nonce_len - tag_len,
-                              decrypted, &decrypted_len,
-                              ciphertext + ciphertext_len - tag_len, tag_len );
-    /* Checking the return code is CRITICAL for security here */
-    if (ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED) {
-        mbedtls_printf("Something bad is happening! Data is not authentic!\r\n");
-        return 1;
-    }
-    if (ret != 0) {
-        mbedtls_printf("mbedtls_cipher_authdecrypt() returned -0x%04X\r\n", -ret);
-        return 1;
-    }
-
-    print_hex("decrypted", decrypted, decrypted_len);
-
-    mbedtls_printf("\r\nDONE\r\n");
-
-    return 0;
+    return exit_code;
 }
-
-int main() {
-    int ret = example();
-    if (ret != 0) {
-        mbedtls_printf("Example failed with error %d\r\n", ret);
-    }
-}