2 * QEMU Crypto hash algorithms
4 * Copyright (c) 2016 Red Hat, Inc.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "qemu/osdep.h"
23 #include "qapi/error.h"
24 #include "crypto/hash.h"
28 static int qcrypto_hash_alg_map
[QCRYPTO_HASH_ALG__MAX
] = {
29 [QCRYPTO_HASH_ALG_MD5
] = GCRY_MD_MD5
,
30 [QCRYPTO_HASH_ALG_SHA1
] = GCRY_MD_SHA1
,
31 [QCRYPTO_HASH_ALG_SHA224
] = GCRY_MD_SHA224
,
32 [QCRYPTO_HASH_ALG_SHA256
] = GCRY_MD_SHA256
,
33 [QCRYPTO_HASH_ALG_SHA384
] = GCRY_MD_SHA384
,
34 [QCRYPTO_HASH_ALG_SHA512
] = GCRY_MD_SHA512
,
35 [QCRYPTO_HASH_ALG_RIPEMD160
] = GCRY_MD_RMD160
,
38 gboolean
qcrypto_hash_supports(QCryptoHashAlgorithm alg
)
40 if (alg
< G_N_ELEMENTS(qcrypto_hash_alg_map
) &&
41 qcrypto_hash_alg_map
[alg
] != GCRY_MD_NONE
) {
49 qcrypto_gcrypt_hash_bytesv(QCryptoHashAlgorithm alg
,
50 const struct iovec
*iov
,
58 unsigned char *digest
;
60 if (!qcrypto_hash_supports(alg
)) {
62 "Unknown hash algorithm %d",
67 ret
= gcry_md_open(&md
, qcrypto_hash_alg_map
[alg
], 0);
71 "Unable to initialize hash algorithm: %s",
76 for (i
= 0; i
< niov
; i
++) {
77 gcry_md_write(md
, iov
[i
].iov_base
, iov
[i
].iov_len
);
80 ret
= gcry_md_get_algo_dlen(qcrypto_hash_alg_map
[alg
]);
83 "Unable to get hash length: %s",
87 if (*resultlen
== 0) {
89 *result
= g_new0(uint8_t, *resultlen
);
90 } else if (*resultlen
!= ret
) {
92 "Result buffer size %zu is smaller than hash %d",
97 digest
= gcry_md_read(md
, 0);
100 "No digest produced");
103 memcpy(*result
, digest
, *resultlen
);
114 QCryptoHashDriver qcrypto_hash_lib_driver
= {
115 .hash_bytesv
= qcrypto_gcrypt_hash_bytesv
,