title: Proper implementation for mbed TLS AES-CTR?
body: <p>I'm using this library: <a href="https://tls.mbed.org/download" rel="nofollow noreferrer">https://tls.mbed.org/download</a> with an Espressif ESP32. The goal is to encrypt some data using AES-CTR then decrypt the cypher-text back to the original plain-text. I am getting incorrect result after I've decrypted.</p>
  
  <p>Since we're using CTR mode, we don't need to have a separate "decrypt" function; We can just call the encrypt function once to encrypt then call the same function one more time and it should decrypt. At least, that's what most sources say and that was the case with this other implementation: <a href="https://github.com/kokke/tiny-AES-c" rel="nofollow noreferrer">https://github.com/kokke/tiny-AES-c</a></p>
  
  <p>I tried using the same nonce, same stream-block, different nonces, different stream-blocks, set the key before each of the function calls, etc. </p>
  
  <pre class="lang-c prettyprint-override"><code>    mbedtls_aes_context aes;
      unsigned char key[16];
      size_t plainText_len = 64;
      unsigned int nc_off = 0;
      unsigned char nonce_counter[16] = {0};
      unsigned char stream_block[16] = {0};
      unsigned char plainText[64] = {0x48, 0x45, 0x4c, 0x4c, 0x4f};
      unsigned char encryptText[64];
      unsigned char decryptText[64];
      memcpy(key, key_128, 16); //key_128 comes from a different file
  
      //Print Key
      printf("aes Key: \n");
      for(int i = 0; i &lt; 16; i++){
          printf("%x",key[i]);
      }
      printf("\n");
  
      //Print plain-text
      printf("aes plainText: \n");
      for(int i = 0; i &lt; 5; i++){
          printf("%x",plainText[i]);
      }
      printf("\n");
  
      esp_aes_init(&amp;aes); //context is initialized
      esp_aes_setkey(&amp;aes, key, 128); //key is associated to context
      esp_aes_crypt_ctr(&amp;aes, plainText_len, &amp;nc_off, nonce_counter, stream_block, plainText, encryptText); //encrypt
  
      //Print encrypt-text
      printf("aes encryptText: \n");
      for(int i = 0; i &lt; 5; i++){
          printf("%x",encryptText[i]);
      }
      printf("\n");
  
      esp_aes_crypt_ctr(&amp;aes, plainText_len, &amp;nc_off, nonce_counter, stream_block, encryptText, decryptText); //decrypt
  
      //Print decrypt-text
      printf("aes decrypt: \n");
      for(int i = 0; i &lt; 5; i++){
          printf("%x",decryptText[i]);
      }
      printf("\n");
  </code></pre>
  
  <p>After the encrypt function is called a second time the resulting decryptText should be the same as the original plain-text, however, at the moment plainText =/= decryptText.</p>
  
  <p>This is what my monitor is printing:</p>
  
  <pre><code>aes key: 7d3043fb95355e6ccd850ad8debc279
  aes plainText: 48454c4c4f
  aes encryptText: 852b97da59
  aes decryptText: 814268329f
  </code></pre>
  
  <p>As you can see, I'm missing <em>something</em> that'll properly decrypt the encryptText!</p>