Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / extlibs / tinydtls / ecc / test / test_ecdh.c
1 /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
2
3 #include "../ecc.h"
4
5 #include <stdio.h>
6 #include <string.h>
7
8 #if LPC11XX
9
10 #include "/Projects/lpc11xx/peripherals/uart.h"
11 #include "/Projects/lpc11xx/peripherals/time.h"
12
13 static uint64_t g_rand = 88172645463325252ull;
14 int fake_rng(uint8_t *p_dest, unsigned p_size)
15 {
16     while(p_size)
17     {
18         g_rand ^= (g_rand << 13);
19         g_rand ^= (g_rand >> 7);
20         g_rand ^= (g_rand << 17);
21
22         unsigned l_amount = (p_size > 8 ? 8 : p_size);
23         memcpy(p_dest, &g_rand, l_amount);
24         p_size -= l_amount;
25     }
26     return 1;
27 }
28
29 #endif
30
31 void vli_print(uint8_t *p_vli, unsigned int p_size)
32 {
33     while(p_size)
34     {
35         printf("%02X ", (unsigned)p_vli[p_size - 1]);
36         --p_size;
37     }
38 }
39
40 int main()
41 {
42 #if LPC11XX
43     uartInit(BAUD_115200);
44         initTime();
45
46     uECC_set_rng(&fake_rng);
47 #endif
48
49     int i;
50
51     uint8_t l_private1[uECC_BYTES];
52     uint8_t l_private2[uECC_BYTES];
53
54     uint8_t l_public1[uECC_BYTES * 2];
55     uint8_t l_public2[uECC_BYTES * 2];
56
57     uint8_t l_secret1[uECC_BYTES];
58     uint8_t l_secret2[uECC_BYTES];
59
60     printf("Testing 256 random private key pairs\n");
61
62     for(i=0; i<256; ++i)
63     {
64         printf(".");
65     #if !LPC11XX
66         fflush(stdout);
67     #endif
68
69         if(!uECC_make_key(l_public1, l_private1) || !uECC_make_key(l_public2, l_private2))
70         {
71             printf("uECC_make_key() failed\n");
72             return 1;
73         }
74
75         if(!uECC_shared_secret(l_public2, l_private1, l_secret1))
76         {
77             printf("shared_secret() failed (1)\n");
78             return 1;
79         }
80
81         if(!uECC_shared_secret(l_public1, l_private2, l_secret2))
82         {
83             printf("shared_secret() failed (2)\n");
84             return 1;
85         }
86
87         if(memcmp(l_secret1, l_secret2, sizeof(l_secret1)) != 0)
88         {
89             printf("Shared secrets are not identical!\n");
90             printf("Shared secret 1 = ");
91             vli_print(l_secret1, uECC_BYTES);
92             printf("\n");
93             printf("Shared secret 2 = ");
94             vli_print(l_secret2, uECC_BYTES);
95             printf("\n");
96             printf("Private key 1 = ");
97             vli_print(l_private1, uECC_BYTES);
98             printf("\n");
99             printf("Private key 2 = ");
100             vli_print(l_private2, uECC_BYTES);
101             printf("\n");
102         }
103     }
104     printf("\n");
105
106     return 0;
107 }