xref: /qemu/tests/bench/benchmark-crypto-hmac.c (revision 7cebff0d)
1 /*
2  * QEMU Crypto hmac speed benchmark
3  *
4  * Copyright (c) 2017 HUAWEI TECHNOLOGIES CO., LTD.
5  *
6  * Authors:
7  *    Longpeng(Mike) <longpeng2@huawei.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or
10  * (at your option) any later version.  See the COPYING file in the
11  * top-level directory.
12  */
13 #include "qemu/osdep.h"
14 #include "qemu/units.h"
15 #include "crypto/init.h"
16 #include "crypto/hmac.h"
17 
18 #define KEY "monkey monkey monkey monkey"
19 
20 static void test_hmac_speed(const void *opaque)
21 {
22     size_t chunk_size = (size_t)opaque;
23     QCryptoHmac *hmac = NULL;
24     uint8_t *in = NULL, *out = NULL;
25     size_t out_len = 0;
26     double total = 0.0;
27     struct iovec iov;
28     Error *err = NULL;
29     int ret;
30 
31     if (!qcrypto_hmac_supports(QCRYPTO_HASH_ALG_SHA256)) {
32         return;
33     }
34 
35     in = g_new0(uint8_t, chunk_size);
36     memset(in, g_test_rand_int(), chunk_size);
37 
38     iov.iov_base = (char *)in;
39     iov.iov_len = chunk_size;
40 
41     g_test_timer_start();
42     do {
43         hmac = qcrypto_hmac_new(QCRYPTO_HASH_ALG_SHA256,
44                                 (const uint8_t *)KEY, strlen(KEY), &err);
45         g_assert(err == NULL);
46         g_assert(hmac != NULL);
47 
48         ret = qcrypto_hmac_bytesv(hmac, &iov, 1, &out, &out_len, &err);
49         g_assert(ret == 0);
50         g_assert(err == NULL);
51 
52         qcrypto_hmac_free(hmac);
53 
54         total += chunk_size;
55     } while (g_test_timer_elapsed() < 5.0);
56 
57     total /= MiB;
58     g_test_message("hmac(%s): chunk %zu bytes %.2f MB/sec",
59                    QCryptoHashAlgorithm_str(QCRYPTO_HASH_ALG_SHA256),
60                    chunk_size, total / g_test_timer_last());
61 
62     g_free(out);
63     g_free(in);
64 }
65 
66 int main(int argc, char **argv)
67 {
68     size_t i;
69     char name[64];
70 
71     g_test_init(&argc, &argv, NULL);
72     g_assert(qcrypto_init(NULL) == 0);
73 
74     for (i = 512; i <= 64 * KiB; i *= 2) {
75         memset(name, 0 , sizeof(name));
76         snprintf(name, sizeof(name), "/crypto/hmac/speed-%zu", i);
77         g_test_add_data_func(name, (void *)i, test_hmac_speed);
78     }
79 
80     return g_test_run();
81 }
82