Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / extlibs / tinydtls / ecc / test / ecc_test / ecc_test.ino
1 #include <uECC.h>
2
3 #include <j0g.h>
4 #include <js0n.h>
5
6 #include <lwm.h>
7
8 #include <bitlash.h>
9
10 #include <GS.h>
11
12 #include <SPI.h>
13 #include <Wire.h>
14 #include <Scout.h>
15 #include <Shell.h>
16
17
18 #include <uECC.h>
19
20 extern "C" {
21
22 static int RNG(uint8_t *p_dest, unsigned p_size)
23 {
24   // Use the least-significant bits from the ADC for an unconnected pin (or connected to a source of random noise)
25   // This can take a long time to generate random data if the result of analogRead(0) doesn't change very frequently.
26   while(p_size) {
27     uint8_t l_val = 0;
28     for(unsigned i=0; i<8; ++i)
29     {
30       int l_init = analogRead(0);
31       int l_count = 0;
32       while(analogRead(0) == l_init)
33       {
34         ++l_count;
35       }
36       
37       if(l_count == 0)
38       {
39          l_val = (l_val << 1) | (l_init & 0x01);
40       }
41       else
42       {
43          l_val = (l_val << 1) | (l_count & 0x01);
44       }
45     }
46     *p_dest = l_val;
47     ++p_dest;
48     --p_size;
49   }
50   
51   // NOTE: it would be a good idea to hash the resulting random data using SHA-256 or similar.
52   return 1;
53 }
54
55 }
56
57 void setup()
58 {
59   Scout.setup();
60   
61   Serial.print("Testing ecc\n");
62   
63   uECC_set_rng(&RNG);
64 }
65
66 void loop() {
67   uint8_t l_private1[uECC_BYTES];
68   uint8_t l_private2[uECC_BYTES];
69   
70   uint8_t l_public1[uECC_BYTES * 2];
71   uint8_t l_public2[uECC_BYTES * 2];
72   
73   uint8_t l_secret1[uECC_BYTES];
74   uint8_t l_secret2[uECC_BYTES];
75   
76   unsigned long a = millis();
77   uECC_make_key(l_public1, l_private1);
78   unsigned long b = millis();
79   
80   Serial.print("Made key 1 in "); Serial.println(b-a);
81   a = millis();
82   uECC_make_key(l_public2, l_private2);
83   b = millis();
84   Serial.print("Made key 2 in "); Serial.println(b-a);
85
86   a = millis();
87   int r = uECC_shared_secret(l_public2, l_private1, l_secret1);
88   b = millis();
89   Serial.print("Shared secret 1 in "); Serial.println(b-a);
90   if(!r)
91   {
92     Serial.print("shared_secret() failed (1)\n");
93     return;
94   }
95
96   a = millis();
97   r = uECC_shared_secret(l_public1, l_private2, l_secret2);
98   b = millis();
99   Serial.print("Shared secret 2 in "); Serial.println(b-a);
100   if(!r)
101   {
102     Serial.print("shared_secret() failed (2)\n");
103     return;
104   }
105     
106   if(memcmp(l_secret1, l_secret2, sizeof(l_secret1)) != 0)
107   {
108     Serial.print("Shared secrets are not identical!\n");
109   }
110   else
111   {
112     Serial.print("Shared secrets are identical\n");
113   }
114 }
115