]> git.proxmox.com Git - mirror_qemu.git/blame - crypto/hash-glib.c
i386: Don't override -cpu options on -cpu host/max
[mirror_qemu.git] / crypto / hash-glib.c
CommitLineData
2165477c
DB
1/*
2 * QEMU Crypto hash algorithms
3 *
4 * Copyright (c) 2016 Red Hat, Inc.
5 *
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 of the License, or (at your option) any later version.
10 *
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.
15 *
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/>.
18 *
19 */
20
21#include "qemu/osdep.h"
22#include "qapi/error.h"
23#include "crypto/hash.h"
24
25
26static int qcrypto_hash_alg_map[QCRYPTO_HASH_ALG__MAX] = {
27 [QCRYPTO_HASH_ALG_MD5] = G_CHECKSUM_MD5,
28 [QCRYPTO_HASH_ALG_SHA1] = G_CHECKSUM_SHA1,
29 [QCRYPTO_HASH_ALG_SHA224] = -1,
30 [QCRYPTO_HASH_ALG_SHA256] = G_CHECKSUM_SHA256,
31 [QCRYPTO_HASH_ALG_SHA384] = -1,
32#if GLIB_CHECK_VERSION(2, 36, 0)
33 [QCRYPTO_HASH_ALG_SHA512] = G_CHECKSUM_SHA512,
34#else
35 [QCRYPTO_HASH_ALG_SHA512] = -1,
36#endif
37 [QCRYPTO_HASH_ALG_RIPEMD160] = -1,
38};
39
40gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)
41{
42 if (alg < G_N_ELEMENTS(qcrypto_hash_alg_map) &&
43 qcrypto_hash_alg_map[alg] != -1) {
44 return true;
45 }
46 return false;
47}
48
49
50int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,
51 const struct iovec *iov,
52 size_t niov,
53 uint8_t **result,
54 size_t *resultlen,
55 Error **errp)
56{
57 int i, ret;
58 GChecksum *cs;
59
76032897 60 if (!qcrypto_hash_supports(alg)) {
2165477c
DB
61 error_setg(errp,
62 "Unknown hash algorithm %d",
63 alg);
64 return -1;
65 }
66
67 cs = g_checksum_new(qcrypto_hash_alg_map[alg]);
68
69 for (i = 0; i < niov; i++) {
70 g_checksum_update(cs, iov[i].iov_base, iov[i].iov_len);
71 }
72
73 ret = g_checksum_type_get_length(qcrypto_hash_alg_map[alg]);
74 if (ret < 0) {
75 error_setg(errp, "%s",
76 "Unable to get hash length");
77 goto error;
78 }
79 if (*resultlen == 0) {
80 *resultlen = ret;
81 *result = g_new0(uint8_t, *resultlen);
82 } else if (*resultlen != ret) {
83 error_setg(errp,
84 "Result buffer size %zu is smaller than hash %d",
85 *resultlen, ret);
86 goto error;
87 }
88
89 g_checksum_get_digest(cs, *result, resultlen);
90
91 g_checksum_free(cs);
92 return 0;
93
94 error:
95 g_checksum_free(cs);
96 return -1;
97}