2
* QEMU Crypto hmac algorithms (based on libgcrypt)
4
* Copyright (c) 2016 HUAWEI TECHNOLOGIES CO., LTD.
7
* Longpeng(Mike) <longpeng2@huawei.com>
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
QCryptoHmac *qcrypto_hmac_new(QCryptoHashAlgorithm alg,
46
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
hmac = g_new0(QCryptoHmac, 1);
62
ctx = g_new0(QCryptoHmacGcrypt, 1);
64
err = gcry_mac_open(&ctx->handle, qcrypto_hmac_alg_map[alg],
65
GCRY_MAC_FLAG_SECURE, NULL);
67
error_setg(errp, "Cannot initialize hmac: %s",
72
err = gcry_mac_setkey(ctx->handle, (const void *)key, nkey);
74
error_setg(errp, "Cannot set key: %s",
88
void qcrypto_hmac_free(QCryptoHmac *hmac)
90
QCryptoHmacGcrypt *ctx;
97
gcry_mac_close(ctx->handle);
103
int qcrypto_hmac_bytesv(QCryptoHmac *hmac,
104
const struct iovec *iov,
110
QCryptoHmacGcrypt *ctx;
117
for (i = 0; i < niov; i++) {
118
gcry_mac_write(ctx->handle, iov[i].iov_base, iov[i].iov_len);
121
ret = gcry_mac_get_algo_maclen(qcrypto_hmac_alg_map[hmac->alg]);
123
error_setg(errp, "Unable to get hmac length: %s",
128
if (*resultlen == 0) {
130
*result = g_new0(uint8_t, *resultlen);
131
} else if (*resultlen != ret) {
132
error_setg(errp, "Result buffer size %zu is smaller than hmac %d",
137
err = gcry_mac_read(ctx->handle, *result, resultlen);
139
error_setg(errp, "Cannot get result: %s",
144
err = gcry_mac_reset(ctx->handle);
146
error_setg(errp, "Cannot reset hmac context: %s",