xref: /freebsd/sys/contrib/libsodium/test/default/kdf.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
1 
2 #define TEST_NAME "kdf"
3 #include "cmptest.h"
4 
5 static void
6 tv_kdf(void)
7 {
8     unsigned char *master_key;
9     unsigned char *subkey;
10     char          *context;
11     char           hex[crypto_kdf_BYTES_MAX * 2 + 1];
12     uint64_t       i;
13     int            ret;
14 
15     context = (char *) sodium_malloc(crypto_kdf_CONTEXTBYTES);
16     master_key = (unsigned char *) sodium_malloc(crypto_kdf_KEYBYTES);
17 
18     memcpy(context, "KDF test", strlen("KDF test"));
19     for (i = 0; i < crypto_kdf_KEYBYTES; i++) {
20         master_key[i] = i;
21     }
22     subkey = (unsigned char *) sodium_malloc(crypto_kdf_BYTES_MAX);
23     for (i = 0; i < 10; i++) {
24         ret = crypto_kdf_derive_from_key(subkey, crypto_kdf_BYTES_MAX,
25                                          i, context, master_key);
26         assert(ret == 0);
27         sodium_bin2hex(hex, sizeof hex, subkey, crypto_kdf_BYTES_MAX);
28         printf("%s\n", hex);
29     }
30     sodium_free(subkey);
31 
32     for (i = 0; i < crypto_kdf_BYTES_MAX + 2; i++) {
33         subkey = (unsigned char *) sodium_malloc(crypto_kdf_BYTES_MAX);
34         if (crypto_kdf_derive_from_key(subkey, (size_t) i,
35                                        i, context, master_key) == 0) {
36             sodium_bin2hex(hex, sizeof hex, subkey, (size_t) i);
37             printf("%s\n", hex);
38         } else {
39             printf("Failure -- probably expected for output length=%u\n",
40                    (unsigned int) i);
41         }
42         sodium_free(subkey);
43     }
44 
45     sodium_free(master_key);
46     sodium_free(context);
47 
48     assert(strcmp(crypto_kdf_primitive(), crypto_kdf_PRIMITIVE) == 0);
49     assert(crypto_kdf_BYTES_MAX > 0);
50     assert(crypto_kdf_BYTES_MIN <= crypto_kdf_BYTES_MAX);
51     assert(crypto_kdf_bytes_min() == crypto_kdf_BYTES_MIN);
52     assert(crypto_kdf_bytes_max() == crypto_kdf_BYTES_MAX);
53     assert(crypto_kdf_CONTEXTBYTES > 0);
54     assert(crypto_kdf_contextbytes() == crypto_kdf_CONTEXTBYTES);
55     assert(crypto_kdf_KEYBYTES >= 16);
56     assert(crypto_kdf_keybytes() == crypto_kdf_KEYBYTES);
57     assert(crypto_kdf_bytes_min() == crypto_kdf_blake2b_bytes_min());
58     assert(crypto_kdf_bytes_max() == crypto_kdf_blake2b_bytes_max());
59     assert(crypto_kdf_contextbytes() == crypto_kdf_blake2b_contextbytes());
60     assert(crypto_kdf_keybytes() == crypto_kdf_blake2b_keybytes());
61 
62     printf("tv_kdf: ok\n");
63 }
64 
65 int
66 main(void)
67 {
68     tv_kdf();
69 
70     return 0;
71 }
72