xref: /openbmc/qemu/crypto/pbkdf-nettle.c (revision 37788f25)
1 /*
2  * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
3  *
4  * Copyright (c) 2015-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 "crypto/pbkdf.h"
23 #include "nettle/pbkdf2.h"
24 
25 
26 bool qcrypto_pbkdf2_supports(QCryptoHashAlgorithm hash)
27 {
28     switch (hash) {
29     case QCRYPTO_HASH_ALG_SHA1:
30     case QCRYPTO_HASH_ALG_SHA256:
31         return true;
32     default:
33         return false;
34     }
35 }
36 
37 int qcrypto_pbkdf2(QCryptoHashAlgorithm hash,
38                    const uint8_t *key, size_t nkey,
39                    const uint8_t *salt, size_t nsalt,
40                    unsigned int iterations,
41                    uint8_t *out, size_t nout,
42                    Error **errp)
43 {
44     switch (hash) {
45     case QCRYPTO_HASH_ALG_SHA1:
46         pbkdf2_hmac_sha1(nkey, key,
47                          iterations,
48                          nsalt, salt,
49                          nout, out);
50         break;
51 
52     case QCRYPTO_HASH_ALG_SHA256:
53         pbkdf2_hmac_sha256(nkey, key,
54                            iterations,
55                            nsalt, salt,
56                            nout, out);
57         break;
58 
59     default:
60         error_setg_errno(errp, ENOSYS,
61                          "PBKDF does not support hash algorithm %d", hash);
62         return -1;
63     }
64     return 0;
65 }
66