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#ifndef _WIN32
25#include <sys/resource.h>
26#endif
27
28
29static int qcrypto_pbkdf2_get_thread_cpu(unsigned long long *val_ms,
30 Error **errp)
31{
32#ifdef _WIN32
33 FILETIME creation_time, exit_time, kernel_time, user_time;
34 ULARGE_INTEGER thread_time;
35
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;
40 }
41
42 thread_time.LowPart = user_time.dwLowDateTime;
43 thread_time.HighPart = user_time.dwHighDateTime;
44
45
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;
53 }
54
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
63}
64
65uint64_t qcrypto_pbkdf2_count_iters(QCryptoHashAlgorithm hash,
66 const uint8_t *key, size_t nkey,
67 const uint8_t *salt, size_t nsalt,
68 size_t nout,
69 Error **errp)
70{
71 uint64_t ret = -1;
72 uint8_t *out;
73 uint64_t iterations = (1 << 15);
74 unsigned long long delta_ms, start_ms, end_ms;
75
76 out = g_new(uint8_t, nout);
77
78 while (1) {
79 if (qcrypto_pbkdf2_get_thread_cpu(&start_ms, errp) < 0) {
80 goto cleanup;
81 }
82 if (qcrypto_pbkdf2(hash,
83 key, nkey,
84 salt, nsalt,
85 iterations,
86 out, nout,
87 errp) < 0) {
88 goto cleanup;
89 }
90 if (qcrypto_pbkdf2_get_thread_cpu(&end_ms, errp) < 0) {
91 goto cleanup;
92 }
93
94 delta_ms = end_ms - start_ms;
95
96 if (delta_ms > 500) {
97 break;
98 } else if (delta_ms < 100) {
99 iterations = iterations * 10;
100 } else {
101 iterations = (iterations * 1000 / delta_ms);
102 }
103 }
104
105 iterations = iterations * 1000 / delta_ms;
106
107 ret = iterations;
108
109 cleanup:
110 memset(out, 0, nout);
111 g_free(out);
112 return ret;
113}
114