xref: /qemu/crypto/hmac.c (revision 33848cee)
1 /*
2  * QEMU Crypto hmac algorithms
3  *
4  * Copyright (c) 2016 HUAWEI TECHNOLOGIES CO., LTD.
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or
7  * (at your option) any later version.  See the COPYING file in the
8  * top-level directory.
9  *
10  */
11 
12 #include "qemu/osdep.h"
13 #include "qapi/error.h"
14 #include "crypto/hmac.h"
15 
16 static const char hex[] = "0123456789abcdef";
17 
18 int qcrypto_hmac_bytes(QCryptoHmac *hmac,
19                        const char *buf,
20                        size_t len,
21                        uint8_t **result,
22                        size_t *resultlen,
23                        Error **errp)
24 {
25     struct iovec iov = {
26             .iov_base = (char *)buf,
27             .iov_len = len
28     };
29 
30     return qcrypto_hmac_bytesv(hmac, &iov, 1, result, resultlen, errp);
31 }
32 
33 int qcrypto_hmac_digestv(QCryptoHmac *hmac,
34                          const struct iovec *iov,
35                          size_t niov,
36                          char **digest,
37                          Error **errp)
38 {
39     uint8_t *result = NULL;
40     size_t resultlen = 0;
41     size_t i;
42 
43     if (qcrypto_hmac_bytesv(hmac, iov, niov, &result, &resultlen, errp) < 0) {
44         return -1;
45     }
46 
47     *digest = g_new0(char, (resultlen * 2) + 1);
48 
49     for (i = 0 ; i < resultlen ; i++) {
50         (*digest)[(i * 2)] = hex[(result[i] >> 4) & 0xf];
51         (*digest)[(i * 2) + 1] = hex[result[i] & 0xf];
52     }
53 
54     (*digest)[resultlen * 2] = '\0';
55 
56     g_free(result);
57     return 0;
58 }
59 
60 int qcrypto_hmac_digest(QCryptoHmac *hmac,
61                         const char *buf,
62                         size_t len,
63                         char **digest,
64                         Error **errp)
65 {
66     struct iovec iov = {
67             .iov_base = (char *)buf,
68             .iov_len = len
69     };
70 
71     return qcrypto_hmac_digestv(hmac, &iov, 1, digest, errp);
72 }
73