block/nfs: add support for libnfs pagecache
[qemu.git] / crypto / pbkdf.c
blob695cc35df1b80692b06e626ac48acf132ed0670b
1 /*
2 * QEMU Crypto PBKDF support (Password-Based Key Derivation Function)
4 * Copyright (c) 2015-2016 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 "qapi/error.h"
23 #include "crypto/pbkdf.h"
24 #ifndef _WIN32
25 #include <sys/resource.h>
26 #endif
29 static int qcrypto_pbkdf2_get_thread_cpu(unsigned long long *val_ms,
30 Error **errp)
32 #ifdef _WIN32
33 FILETIME creation_time, exit_time, kernel_time, user_time;
34 ULARGE_INTEGER thread_time;
36 if (!GetThreadTimes(GetCurrentThread(), &creation_time, &exit_time,
37 &kernel_time, &user_time)) {
38 error_setg(errp, "Unable to get thread CPU usage");
39 return -1;
42 thread_time.LowPart = user_time.dwLowDateTime;
43 thread_time.HighPart = user_time.dwHighDateTime;
45 /* QuadPart is units of 100ns and we want ms as unit */
46 *val_ms = thread_time.QuadPart / 10000ll;
47 return 0;
48 #elif defined(RUSAGE_THREAD)
49 struct rusage ru;
50 if (getrusage(RUSAGE_THREAD, &ru) < 0) {
51 error_setg_errno(errp, errno, "Unable to get thread CPU usage");
52 return -1;
55 *val_ms = ((ru.ru_utime.tv_sec * 1000ll) +
56 (ru.ru_utime.tv_usec / 1000));
57 return 0;
58 #else
59 *val_ms = 0;
60 error_setg(errp, "Unable to calculate thread CPU usage on this platform");
61 return -1;
62 #endif
65 int qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash,
66 const uint8_t *key, size_t nkey,
67 const uint8_t *salt, size_t nsalt,
68 Error **errp)
70 uint8_t out[32];
71 long long int iterations = (1 << 15);
72 unsigned long long delta_ms, start_ms, end_ms;
74 while (1) {
75 if (qcrypto_pbkdf2_get_thread_cpu(&start_ms, errp) < 0) {
76 return -1;
78 if (qcrypto_pbkdf2(hash,
79 key, nkey,
80 salt, nsalt,
81 iterations,
82 out, sizeof(out),
83 errp) < 0) {
84 return -1;
86 if (qcrypto_pbkdf2_get_thread_cpu(&end_ms, errp) < 0) {
87 return -1;
90 delta_ms = end_ms - start_ms;
92 if (delta_ms > 500) {
93 break;
94 } else if (delta_ms < 100) {
95 iterations = iterations * 10;
96 } else {
97 iterations = (iterations * 1000 / delta_ms);
101 iterations = iterations * 1000 / delta_ms;
103 if (iterations > INT32_MAX) {
104 error_setg(errp, "Iterations %lld too large for a 32-bit int",
105 iterations);
106 return -1;
109 return iterations;