1 
2 #define TEST_NAME "secretbox_easy2"
3 #include "cmptest.h"
4 
5 int
6 main(void)
7 {
8     unsigned char *m;
9     unsigned char *m2;
10     unsigned char *c;
11     unsigned char *nonce;
12     unsigned char *k;
13     unsigned char *mac;
14     size_t         mlen;
15     size_t         i;
16 
17     mlen  = (size_t) randombytes_uniform((uint32_t) 10000) + 1U;
18     m     = (unsigned char *) sodium_malloc(mlen);
19     m2    = (unsigned char *) sodium_malloc(mlen);
20     c     = (unsigned char *) sodium_malloc(crypto_secretbox_MACBYTES + mlen);
21     nonce = (unsigned char *) sodium_malloc(crypto_secretbox_NONCEBYTES);
22     k     = (unsigned char *) sodium_malloc(crypto_secretbox_KEYBYTES);
23     mac   = (unsigned char *) sodium_malloc(crypto_secretbox_MACBYTES);
24     crypto_secretbox_keygen(k);
25     randombytes_buf(m, mlen);
26     randombytes_buf(nonce, crypto_secretbox_NONCEBYTES);
27     crypto_secretbox_easy(c, m, (unsigned long long) mlen, nonce, k);
28     if (crypto_secretbox_open_easy(
29             m2, c, (unsigned long long) mlen + crypto_secretbox_MACBYTES, nonce,
30             k) != 0) {
31         printf("crypto_secretbox_open_easy() failed\n");
32     }
33     printf("%d\n", memcmp(m, m2, mlen));
34 
35     for (i = 0; i < mlen + crypto_secretbox_MACBYTES - 1; i++) {
36         if (crypto_secretbox_open_easy(m2, c, (unsigned long long) i, nonce,
37                                        k) == 0) {
38             printf("short open() should have failed\n");
39             return 1;
40         }
41     }
42     crypto_secretbox_detached(c, mac, m, (unsigned long long) mlen, nonce, k);
43     if (crypto_secretbox_open_detached(NULL, c, mac, (unsigned long long) mlen,
44                                        nonce, k) != 0) {
45         printf("crypto_secretbox_open_detached() with a NULL message pointer failed\n");
46     }
47     if (crypto_secretbox_open_detached(m2, c, mac, (unsigned long long) mlen,
48                                        nonce, k) != 0) {
49         printf("crypto_secretbox_open_detached() failed\n");
50     }
51     printf("%d\n", memcmp(m, m2, mlen));
52 
53     memcpy(c, m, mlen);
54     crypto_secretbox_easy(c, c, (unsigned long long) mlen, nonce, k);
55     printf("%d\n", memcmp(m, c, mlen) == 0);
56     printf("%d\n", memcmp(m, c + crypto_secretbox_MACBYTES, mlen) == 0);
57     if (crypto_secretbox_open_easy(
58             c, c, (unsigned long long) mlen + crypto_secretbox_MACBYTES, nonce,
59             k) != 0) {
60         printf("crypto_secretbox_open_easy() failed\n");
61     }
62     printf("%d\n", memcmp(m, c, mlen));
63 
64     sodium_free(m);
65     sodium_free(m2);
66     sodium_free(c);
67     sodium_free(nonce);
68     sodium_free(k);
69     sodium_free(mac);
70 
71     return 0;
72 }
73