1#include <uECC.h> 2 3extern "C" { 4 5static int RNG(uint8_t *dest, unsigned size) { 6 // Use the least-significant bits from the ADC for an unconnected pin (or connected to a source of 7 // random noise). This can take a long time to generate random data if the result of analogRead(0) 8 // doesn't change very frequently. 9 while (size) { 10 uint8_t val = 0; 11 for (unsigned i = 0; i < 8; ++i) { 12 int init = analogRead(0); 13 int count = 0; 14 while (analogRead(0) == init) { 15 ++count; 16 } 17 18 if (count == 0) { 19 val = (val << 1) | (init & 0x01); 20 } else { 21 val = (val << 1) | (count & 0x01); 22 } 23 } 24 *dest = val; 25 ++dest; 26 --size; 27 } 28 // NOTE: it would be a good idea to hash the resulting random data using SHA-256 or similar. 29 return 1; 30} 31 32} // extern "C" 33 34void setup() { 35 Serial.begin(115200); 36 Serial.print("Testing ecc\n"); 37 uECC_set_rng(&RNG); 38} 39 40void loop() { 41 uint8_t private1[uECC_BYTES]; 42 uint8_t private2[uECC_BYTES]; 43 44 uint8_t public1[uECC_BYTES * 2]; 45 uint8_t public2[uECC_BYTES * 2]; 46 47 uint8_t secret1[uECC_BYTES]; 48 uint8_t secret2[uECC_BYTES]; 49 50 unsigned long a = millis(); 51 uECC_make_key(public1, private1); 52 unsigned long b = millis(); 53 54 Serial.print("Made key 1 in "); Serial.println(b-a); 55 a = millis(); 56 uECC_make_key(public2, private2); 57 b = millis(); 58 Serial.print("Made key 2 in "); Serial.println(b-a); 59 60 a = millis(); 61 int r = uECC_shared_secret(public2, private1, secret1); 62 b = millis(); 63 Serial.print("Shared secret 1 in "); Serial.println(b-a); 64 if (!r) { 65 Serial.print("shared_secret() failed (1)\n"); 66 return; 67 } 68 69 a = millis(); 70 r = uECC_shared_secret(public1, private2, secret2); 71 b = millis(); 72 Serial.print("Shared secret 2 in "); Serial.println(b-a); 73 if (!r) { 74 Serial.print("shared_secret() failed (2)\n"); 75 return; 76 } 77 78 if (memcmp(secret1, secret2, sizeof(secret1)) != 0) { 79 Serial.print("Shared secrets are not identical!\n"); 80 } else { 81 Serial.print("Shared secrets are identical\n"); 82 } 83} 84 85