16
#include "qemu/osdep.h"
17
#include <gnutls/crypto.h>
19
#include "qapi/error.h"
20
#include "crypto/hmac.h"
23
static int qcrypto_hmac_alg_map[QCRYPTO_HASH_ALG__MAX] = {
24
[QCRYPTO_HASH_ALG_MD5] = GNUTLS_MAC_MD5,
25
[QCRYPTO_HASH_ALG_SHA1] = GNUTLS_MAC_SHA1,
26
[QCRYPTO_HASH_ALG_SHA224] = GNUTLS_MAC_SHA224,
27
[QCRYPTO_HASH_ALG_SHA256] = GNUTLS_MAC_SHA256,
28
[QCRYPTO_HASH_ALG_SHA384] = GNUTLS_MAC_SHA384,
29
[QCRYPTO_HASH_ALG_SHA512] = GNUTLS_MAC_SHA512,
30
[QCRYPTO_HASH_ALG_RIPEMD160] = GNUTLS_MAC_RMD160,
33
typedef struct QCryptoHmacGnutls QCryptoHmacGnutls;
34
struct QCryptoHmacGnutls {
35
gnutls_hmac_hd_t handle;
38
bool qcrypto_hmac_supports(QCryptoHashAlgorithm alg)
41
const gnutls_digest_algorithm_t *algs;
42
if (alg >= G_N_ELEMENTS(qcrypto_hmac_alg_map) ||
43
qcrypto_hmac_alg_map[alg] == GNUTLS_DIG_UNKNOWN) {
46
algs = gnutls_digest_list();
47
for (i = 0; algs[i] != GNUTLS_DIG_UNKNOWN; i++) {
48
if (algs[i] == qcrypto_hmac_alg_map[alg]) {
55
void *qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
56
const uint8_t *key, size_t nkey,
59
QCryptoHmacGnutls *ctx;
62
if (!qcrypto_hmac_supports(alg)) {
63
error_setg(errp, "Unsupported hmac algorithm %s",
64
QCryptoHashAlgorithm_str(alg));
68
ctx = g_new0(QCryptoHmacGnutls, 1);
70
err = gnutls_hmac_init(&ctx->handle,
71
qcrypto_hmac_alg_map[alg],
72
(const void *)key, nkey);
74
error_setg(errp, "Cannot initialize hmac: %s",
75
gnutls_strerror(err));
87
qcrypto_gnutls_hmac_ctx_free(QCryptoHmac *hmac)
89
QCryptoHmacGnutls *ctx;
92
gnutls_hmac_deinit(ctx->handle, NULL);
98
qcrypto_gnutls_hmac_bytesv(QCryptoHmac *hmac,
99
const struct iovec *iov,
105
QCryptoHmacGnutls *ctx;
111
for (i = 0; i < niov; i++) {
112
gnutls_hmac(ctx->handle, iov[i].iov_base, iov[i].iov_len);
115
ret = gnutls_hmac_get_len(qcrypto_hmac_alg_map[hmac->alg]);
117
error_setg(errp, "Unable to get hmac length: %s",
118
gnutls_strerror(ret));
122
if (*resultlen == 0) {
124
*result = g_new0(uint8_t, *resultlen);
125
} else if (*resultlen != ret) {
126
error_setg(errp, "Result buffer size %zu is smaller than hmac %d",
131
gnutls_hmac_output(ctx->handle, *result);
136
QCryptoHmacDriver qcrypto_hmac_lib_driver = {
137
.hmac_bytesv = qcrypto_gnutls_hmac_bytesv,
138
.hmac_free = qcrypto_gnutls_hmac_ctx_free,