]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/rand/rand_win.c
Switch from ossl_rand to DRBG rand
[thirdparty/openssl.git] / crypto / rand / rand_win.c
1 /*
2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include "internal/cryptlib.h"
11 #include <openssl/rand.h>
12 #include "rand_lcl.h"
13
14 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
15
16 # ifndef OPENSSL_RAND_SEED_OS
17 # error "Unsupported seeding method configured; must be os"
18 # endif
19
20 # include <windows.h>
21 /* On Windows 7 or higher use BCrypt instead of the legacy CryptoAPI */
22 # if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0601
23 # define USE_BCRYPTGENRANDOM
24 # endif
25
26 # ifdef USE_BCRYPTGENRANDOM
27 # include <bcrypt.h>
28 # pragma comment(lib, "bcrypt.lib")
29 # ifndef STATUS_SUCCESS
30 # define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
31 # endif
32 # else
33 # include <wincrypt.h>
34 /*
35 * Intel hardware RNG CSP -- available from
36 * http://developer.intel.com/design/security/rng/redist_license.htm
37 */
38 # define PROV_INTEL_SEC 22
39 # define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
40 # endif
41
42 int RAND_poll_ex(RAND_poll_fn cb, void *arg)
43 {
44 # ifndef USE_BCRYPTGENRANDOM
45 HCRYPTPROV hProvider;
46 # endif
47 DWORD w;
48 BYTE buf[RANDOMNESS_NEEDED];
49 int ok = 0;
50
51 # ifdef OPENSSL_RAND_SEED_RDTSC
52 rand_read_tsc(cb, arg);
53 # endif
54 # ifdef OPENSSL_RAND_SEED_RDCPU
55 if (rand_read_cpu(cb, arg))
56 ok++;
57 # endif
58
59 # ifdef USE_BCRYPTGENRANDOM
60 if (BCryptGenRandom(NULL, buf, (ULONG)sizeof(buf),
61 BCRYPT_USE_SYSTEM_PREFERRED_RNG) != STATUS_SUCCESS)
62 return 0;
63 cb(arg, buf, sizeof(buf), sizeof(buf));
64 return 1;
65 # else
66 /* poll the CryptoAPI PRNG */
67 if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
68 CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
69 if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
70 cb(arg, buf, sizeof(buf), sizeof(buf));
71 ok++;
72 }
73 CryptReleaseContext(hProvider, 0);
74 }
75
76 /* poll the Pentium PRG with CryptoAPI */
77 if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC,
78 CRYPT_VERIFYCONTEXT | CRYPT_SILENT) != 0) {
79 if (CryptGenRandom(hProvider, (DWORD)sizeof(buf), buf) != 0) {
80 cb(arg, buf, sizeof(buf), sizeof(buf));
81 ok++;
82 }
83 CryptReleaseContext(hProvider, 0);
84 }
85 # endif
86
87 return ok ? 1 : 0;
88 }
89
90 #if OPENSSL_API_COMPAT < 0x10100000L
91 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
92 {
93 RAND_poll();
94 return RAND_status();
95 }
96
97 void RAND_screen(void)
98 {
99 RAND_poll();
100 }
101 #endif
102
103 #endif