1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21#include "qemu/osdep.h"
22#include <gcrypt.h>
23#include "qapi/error.h"
24#include "crypto/pbkdf.h"
25
26bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
27{
28 switch (hash) {
29 case QCRYPTO_HASH_ALG_MD5:
30 case QCRYPTO_HASH_ALG_SHA1:
31 case QCRYPTO_HASH_ALG_SHA224:
32 case QCRYPTO_HASH_ALG_SHA256:
33 case QCRYPTO_HASH_ALG_SHA384:
34 case QCRYPTO_HASH_ALG_SHA512:
35 case QCRYPTO_HASH_ALG_RIPEMD160:
36 return true;
37 default:
38 return false;
39 }
40}
41
42int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
43 const uint8_t *key, size_t nkey,
44 const uint8_t *salt, size_t nsalt,
45 uint64_t iterations,
46 uint8_t *out, size_t nout,
47 Error **errp)
48{
49 static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
50 [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
51 [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
52 [QCRYPTO_HASH_ALG_SHA224] = GCRY_MD_SHA224,
53 [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
54 [QCRYPTO_HASH_ALG_SHA384] = GCRY_MD_SHA384,
55 [QCRYPTO_HASH_ALG_SHA512] = GCRY_MD_SHA512,
56 [QCRYPTO_HASH_ALG_RIPEMD160] = GCRY_MD_RMD160,
57 };
58 int ret;
59
60 if (iterations > ULONG_MAX) {
61 error_setg_errno(errp, ERANGE,
62 "PBKDF iterations %llu must be less than %lu",
63 (long long unsigned)iterations, ULONG_MAX);
64 return -1;
65 }
66
67 if (hash >= G_N_ELEMENTS(hash_map) ||
68 hash_map[hash] == GCRY_MD_NONE) {
69 error_setg_errno(errp, ENOSYS,
70 "PBKDF does not support hash algorithm %s",
71 QCryptoHashAlgorithm_str(hash));
72 return -1;
73 }
74
75 ret = gcry_kdf_derive(key, nkey, GCRY_KDF_PBKDF2,
76 hash_map[hash],
77 salt, nsalt, iterations,
78 nout, out);
79 if (ret != 0) {
80 error_setg(errp, "Cannot derive password: %s",
81 gcry_strerror(ret));
82 return -1;
83 }
84
85 return 0;
86}
87