2 * QEMU Crypto hmac algorithms (based on libgcrypt)
4 * Copyright (c) 2016 HUAWEI TECHNOLOGIES CO., LTD.
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.
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include "crypto/hmac.h"
20 static int qcrypto_hmac_alg_map[QCRYPTO_HASH_ALG__MAX] = {
21 [QCRYPTO_HASH_ALG_MD5] = GCRY_MAC_HMAC_MD5,
22 [QCRYPTO_HASH_ALG_SHA1] = GCRY_MAC_HMAC_SHA1,
23 [QCRYPTO_HASH_ALG_SHA224] = GCRY_MAC_HMAC_SHA224,
24 [QCRYPTO_HASH_ALG_SHA256] = GCRY_MAC_HMAC_SHA256,
25 [QCRYPTO_HASH_ALG_SHA384] = GCRY_MAC_HMAC_SHA384,
26 [QCRYPTO_HASH_ALG_SHA512] = GCRY_MAC_HMAC_SHA512,
27 [QCRYPTO_HASH_ALG_RIPEMD160] = GCRY_MAC_HMAC_RMD160,
30 typedef struct QCryptoHmacGcrypt QCryptoHmacGcrypt;
31 struct QCryptoHmacGcrypt {
35 bool qcrypto_hmac_supports(QCryptoHashAlgorithm alg)
37 if (alg < G_N_ELEMENTS(qcrypto_hmac_alg_map) &&
38 qcrypto_hmac_alg_map[alg] != GCRY_MAC_NONE) {
45 static QCryptoHmacGcrypt *
46 qcrypto_hmac_ctx_new(QCryptoHashAlgorithm alg,
47 const uint8_t *key, size_t nkey,
50 QCryptoHmacGcrypt *ctx;
53 if (!qcrypto_hmac_supports(alg)) {
54 error_setg(errp, "Unsupported hmac algorithm %s",
55 QCryptoHashAlgorithm_lookup[alg]);
59 ctx = g_new0(QCryptoHmacGcrypt, 1);
61 err = gcry_mac_open(&ctx->handle, qcrypto_hmac_alg_map[alg],
62 GCRY_MAC_FLAG_SECURE, NULL);
64 error_setg(errp, "Cannot initialize hmac: %s",
69 err = gcry_mac_setkey(ctx->handle, (const void *)key, nkey);
71 error_setg(errp, "Cannot set key: %s",
73 gcry_mac_close(ctx->handle);
84 void qcrypto_hmac_free(QCryptoHmac *hmac)
86 QCryptoHmacGcrypt *ctx;
93 gcry_mac_close(ctx->handle);
99 int qcrypto_hmac_bytesv(QCryptoHmac *hmac,
100 const struct iovec *iov,
106 QCryptoHmacGcrypt *ctx;
113 for (i = 0; i < niov; i++) {
114 gcry_mac_write(ctx->handle, iov[i].iov_base, iov[i].iov_len);
117 ret = gcry_mac_get_algo_maclen(qcrypto_hmac_alg_map[hmac->alg]);
119 error_setg(errp, "Unable to get hmac length: %s",
124 if (*resultlen == 0) {
126 *result = g_new0(uint8_t, *resultlen);
127 } else if (*resultlen != ret) {
128 error_setg(errp, "Result buffer size %zu is smaller than hmac %d",
133 err = gcry_mac_read(ctx->handle, *result, resultlen);
135 error_setg(errp, "Cannot get result: %s",
140 err = gcry_mac_reset(ctx->handle);
142 error_setg(errp, "Cannot reset hmac context: %s",
150 QCryptoHmac *qcrypto_hmac_new(QCryptoHashAlgorithm alg,
151 const uint8_t *key, size_t nkey,
155 QCryptoHmacGcrypt *ctx;
157 ctx = qcrypto_hmac_ctx_new(alg, key, nkey, errp);
162 hmac = g_new0(QCryptoHmac, 1);