tweetnacl crypto

Dependencies:   mbed

Revision:
0:bed9ac8a7beb
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Feb 27 00:33:36 2018 +0000
@@ -0,0 +1,69 @@
+// https://github.com/rjw245/crypto-in-a-box
+#include "mbed.h"
+#include "tweetnacl.h"
+
+// standalone test
+static const uint8_t secretkey[crypto_secretbox_KEYBYTES] = {
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+  0, 1
+};
+
+static const uint8_t nonce[crypto_secretbox_NONCEBYTES] = {
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+  0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+  0, 1, 2, 3
+};
+
+// Need crypto_secretbox_ZEROBYTES of room at the beginning
+// AND crypto_secretbox_BOXZEROBYTES at the end.
+// The crypto_secretbox_BOXZEROBYTES allows an encrypted input to fit
+// in the buffer when storage STARTS at index [crypto_secretbox_ZEROBYTES]
+#define BUFFER_SIZE (256 + \
+                     crypto_secretbox_ZEROBYTES + \
+                     crypto_secretbox_BOXZEROBYTES)
+
+static unsigned char input_buffer[BUFFER_SIZE], outdata[BUFFER_SIZE];
+static uint8_t input_len = 0;
+
+static const uint8_t msg[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
+
+
+
+Timer tmr;
+
+main() {
+  int r;
+  uint32_t us;
+
+  tmr.start();
+  memset(input_buffer, 0, sizeof(input_buffer));
+  input_len = sizeof(msg);
+  memcpy(input_buffer + crypto_secretbox_ZEROBYTES, msg, input_len);
+  // encrypt
+  us = tmr.read_us();
+  r = crypto_secretbox(outdata,
+                       input_buffer,
+                       input_len + crypto_secretbox_ZEROBYTES,
+                       nonce,
+                       secretkey);
+  us = tmr.read_us() - us;
+  printf("r= %d  %d us\n",r,us);
+
+
+  //decrypt
+  memset(input_buffer, 0, sizeof(input_buffer));
+  us = tmr.read_us();
+  r = crypto_secretbox_open(input_buffer,
+                            outdata,
+                            input_len + crypto_secretbox_ZEROBYTES,
+                            nonce,
+                            secretkey);
+  us = tmr.read_us() - us;
+  printf("r= %d  %d us\n",r,us);
+  for (int i = 0; i < 4; i++) printf("%d ",input_buffer[crypto_secretbox_ZEROBYTES + i]);
+  printf("\n");
+  r = memcmp(msg, input_buffer + crypto_secretbox_ZEROBYTES, input_len);
+  printf("result %d\n",r);
+}
\ No newline at end of file