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"
21 static int qcrypto_hmac_alg_map
[QCRYPTO_HASH_ALGO__MAX
] = {
22 [QCRYPTO_HASH_ALGO_MD5
] = GCRY_MAC_HMAC_MD5
,
23 [QCRYPTO_HASH_ALGO_SHA1
] = GCRY_MAC_HMAC_SHA1
,
24 [QCRYPTO_HASH_ALGO_SHA224
] = GCRY_MAC_HMAC_SHA224
,
25 [QCRYPTO_HASH_ALGO_SHA256
] = GCRY_MAC_HMAC_SHA256
,
26 [QCRYPTO_HASH_ALGO_SHA384
] = GCRY_MAC_HMAC_SHA384
,
27 [QCRYPTO_HASH_ALGO_SHA512
] = GCRY_MAC_HMAC_SHA512
,
28 [QCRYPTO_HASH_ALGO_RIPEMD160
] = GCRY_MAC_HMAC_RMD160
,
31 typedef struct QCryptoHmacGcrypt QCryptoHmacGcrypt
;
32 struct QCryptoHmacGcrypt
{
36 bool qcrypto_hmac_supports(QCryptoHashAlgo alg
)
38 if (alg
< G_N_ELEMENTS(qcrypto_hmac_alg_map
) &&
39 qcrypto_hmac_alg_map
[alg
] != GCRY_MAC_NONE
) {
46 void *qcrypto_hmac_ctx_new(QCryptoHashAlgo 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 QCryptoHashAlgo_str(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
);
85 qcrypto_gcrypt_hmac_ctx_free(QCryptoHmac
*hmac
)
87 QCryptoHmacGcrypt
*ctx
;
90 gcry_mac_close(ctx
->handle
);
96 qcrypto_gcrypt_hmac_bytesv(QCryptoHmac
*hmac
,
97 const struct iovec
*iov
,
103 QCryptoHmacGcrypt
*ctx
;
110 for (i
= 0; i
< niov
; i
++) {
111 gcry_mac_write(ctx
->handle
, iov
[i
].iov_base
, iov
[i
].iov_len
);
114 ret
= gcry_mac_get_algo_maclen(qcrypto_hmac_alg_map
[hmac
->alg
]);
116 error_setg(errp
, "Unable to get hmac length: %s",
121 if (*resultlen
== 0) {
123 *result
= g_new0(uint8_t, *resultlen
);
124 } else if (*resultlen
!= ret
) {
125 error_setg(errp
, "Result buffer size %zu is smaller than hmac %d",
130 err
= gcry_mac_read(ctx
->handle
, *result
, resultlen
);
132 error_setg(errp
, "Cannot get result: %s",
137 err
= gcry_mac_reset(ctx
->handle
);
139 error_setg(errp
, "Cannot reset hmac context: %s",
147 QCryptoHmacDriver qcrypto_hmac_lib_driver
= {
148 .hmac_bytesv
= qcrypto_gcrypt_hmac_bytesv
,
149 .hmac_free
= qcrypto_gcrypt_hmac_ctx_free
,