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 "qapi/error.h"
23#include "crypto/pbkdf.h"
24#include "gcrypt.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_SHA256:
32 return true;
33 default:
34 return false;
35 }
36}
37
38int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
39 const uint8_t *key, size_t nkey,
40 const uint8_t *salt, size_t nsalt,
41 unsigned int iterations,
42 uint8_t *out, size_t nout,
43 Error **errp)
44{
45 static const int hash_map[QCRYPTO_HASH_ALG__MAX] = {
46 [QCRYPTO_HASH_ALG_MD5] = GCRY_MD_MD5,
47 [QCRYPTO_HASH_ALG_SHA1] = GCRY_MD_SHA1,
48 [QCRYPTO_HASH_ALG_SHA256] = GCRY_MD_SHA256,
49 };
50 int ret;
51
52 if (hash >= G_N_ELEMENTS(hash_map) ||
53 hash_map[hash] == GCRY_MD_NONE) {
54 error_setg(errp, "Unexpected hash algorithm %d", hash);
55 return -1;
56 }
57
58 ret = gcry_kdf_derive(key, nkey, GCRY_KDF_PBKDF2,
59 hash_map[hash],
60 salt, nsalt, iterations,
61 nout, out);
62 if (ret != 0) {
63 error_setg(errp, "Cannot derive password: %s",
64 gcry_strerror(ret));
65 return -1;
66 }
67
68 return 0;
69}
70