2 * QEMU Crypto hash algorithms
4 * Copyright (c) 2015 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 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"
22 #include "crypto/hash.h"
25 static size_t qcrypto_hash_alg_size
[QCRYPTO_HASH_ALG__MAX
] = {
26 [QCRYPTO_HASH_ALG_MD5
] = 16,
27 [QCRYPTO_HASH_ALG_SHA1
] = 20,
28 [QCRYPTO_HASH_ALG_SHA224
] = 28,
29 [QCRYPTO_HASH_ALG_SHA256
] = 32,
30 [QCRYPTO_HASH_ALG_SHA384
] = 48,
31 [QCRYPTO_HASH_ALG_SHA512
] = 64,
32 [QCRYPTO_HASH_ALG_RIPEMD160
] = 20,
35 size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg
)
37 assert(alg
< G_N_ELEMENTS(qcrypto_hash_alg_size
));
38 return qcrypto_hash_alg_size
[alg
];
41 int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg
,
42 const struct iovec
*iov
,
52 * Maybe we should treat some afalg errors as fatal
54 ret
= qcrypto_hash_afalg_driver
.hash_bytesv(alg
, iov
, niov
,
62 return qcrypto_hash_lib_driver
.hash_bytesv(alg
, iov
, niov
,
68 int qcrypto_hash_bytes(QCryptoHashAlgorithm alg
,
75 struct iovec iov
= { .iov_base
= (char *)buf
,
77 return qcrypto_hash_bytesv(alg
, &iov
, 1, result
, resultlen
, errp
);
80 static const char hex
[] = "0123456789abcdef";
82 int qcrypto_hash_digestv(QCryptoHashAlgorithm alg
,
83 const struct iovec
*iov
,
88 uint8_t *result
= NULL
;
92 if (qcrypto_hash_bytesv(alg
, iov
, niov
, &result
, &resultlen
, errp
) < 0) {
96 *digest
= g_new0(char, (resultlen
* 2) + 1);
97 for (i
= 0 ; i
< resultlen
; i
++) {
98 (*digest
)[(i
* 2)] = hex
[(result
[i
] >> 4) & 0xf];
99 (*digest
)[(i
* 2) + 1] = hex
[result
[i
] & 0xf];
101 (*digest
)[resultlen
* 2] = '\0';
106 int qcrypto_hash_digest(QCryptoHashAlgorithm alg
,
112 struct iovec iov
= { .iov_base
= (char *)buf
, .iov_len
= len
};
114 return qcrypto_hash_digestv(alg
, &iov
, 1, digest
, errp
);
117 int qcrypto_hash_base64v(QCryptoHashAlgorithm alg
,
118 const struct iovec
*iov
,
123 uint8_t *result
= NULL
;
124 size_t resultlen
= 0;
126 if (qcrypto_hash_bytesv(alg
, iov
, niov
, &result
, &resultlen
, errp
) < 0) {
130 *base64
= g_base64_encode(result
, resultlen
);
135 int qcrypto_hash_base64(QCryptoHashAlgorithm alg
,
141 struct iovec iov
= { .iov_base
= (char *)buf
, .iov_len
= len
};
143 return qcrypto_hash_base64v(alg
, &iov
, 1, base64
, errp
);