xref: /freebsd/sys/contrib/libsodium/test/default/box8.c (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
1 
2 #define TEST_NAME "box8"
3 #include "cmptest.h"
4 
5 static unsigned char alicesk[crypto_box_SECRETKEYBYTES];
6 static unsigned char alicepk[crypto_box_PUBLICKEYBYTES];
7 static unsigned char bobsk[crypto_box_SECRETKEYBYTES];
8 static unsigned char bobpk[crypto_box_PUBLICKEYBYTES];
9 static unsigned char n[crypto_box_NONCEBYTES];
10 
11 int
12 main(void)
13 {
14     unsigned char *m;
15     unsigned char *c;
16     unsigned char *m2;
17     size_t         mlen;
18     size_t         mlen_max = 1000;
19     size_t         i;
20     int            faults;
21     int            ret;
22 
23     m  = (unsigned char *) sodium_malloc(mlen_max);
24     c  = (unsigned char *) sodium_malloc(mlen_max);
25     m2 = (unsigned char *) sodium_malloc(mlen_max);
26     crypto_box_keypair(alicepk, alicesk);
27     crypto_box_keypair(bobpk, bobsk);
28     for (mlen = 0; mlen + crypto_box_ZEROBYTES <= mlen_max; mlen++) {
29         randombytes_buf(n, crypto_box_NONCEBYTES);
30         randombytes_buf(m + crypto_box_ZEROBYTES, mlen);
31         ret = crypto_box(c, m, mlen + crypto_box_ZEROBYTES, n, bobpk, alicesk);
32         assert(ret == 0);
33 #ifdef BROWSER_TESTS
34         faults = 1;
35 #else
36         faults = 5;
37 #endif
38         while (faults > 0) {
39             c[rand() % (mlen + crypto_box_ZEROBYTES)] = rand();
40             if (crypto_box_open(m2, c, mlen + crypto_box_ZEROBYTES, n, alicepk,
41                                 bobsk) == 0) {
42                 for (i = 0; i < mlen + crypto_box_ZEROBYTES; ++i) {
43                     if (m2[i] != m[i]) {
44                         printf("forgery\n");
45                         return 100;
46                     }
47                 }
48             } else {
49                 faults--;
50             }
51         }
52     }
53     sodium_free(m);
54     sodium_free(c);
55     sodium_free(m2);
56 
57     return 0;
58 }
59