FreeRDP
rand.c
1 
19 #include <winpr/config.h>
20 
21 #include <winpr/crt.h>
22 
23 #include <winpr/crypto.h>
24 
25 #ifdef WITH_OPENSSL
26 #include <openssl/crypto.h>
27 #include <openssl/rand.h>
28 #endif
29 
30 #ifdef WITH_MBEDTLS
31 #include <mbedtls/md.h>
32 #include <mbedtls/entropy.h>
33 #ifdef MBEDTLS_HAVEGE_C
34 #include <mbedtls/havege.h>
35 #endif
36 #include <mbedtls/hmac_drbg.h>
37 #endif
38 
39 int winpr_RAND(void* output, size_t len)
40 {
41 #if defined(WITH_OPENSSL)
42  if (len > INT_MAX)
43  return -1;
44  if (RAND_bytes(output, (int)len) != 1)
45  return -1;
46 #elif defined(WITH_MBEDTLS)
47 #if defined(MBEDTLS_HAVEGE_C)
48  mbedtls_havege_state hs;
49  mbedtls_havege_init(&hs);
50 
51  if (mbedtls_havege_random(&hs, output, len) != 0)
52  return -1;
53 
54  mbedtls_havege_free(&hs);
55 #else
56  int status;
57  mbedtls_entropy_context entropy;
58  mbedtls_hmac_drbg_context hmac_drbg;
59  const mbedtls_md_info_t* md_info;
60 
61  mbedtls_entropy_init(&entropy);
62  mbedtls_hmac_drbg_init(&hmac_drbg);
63 
64  md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
65  if ((status = mbedtls_hmac_drbg_seed(&hmac_drbg, md_info, mbedtls_entropy_func, &entropy, NULL,
66  0)) != 0)
67  return -1;
68 
69  status = mbedtls_hmac_drbg_random(&hmac_drbg, output, len);
70  mbedtls_hmac_drbg_free(&hmac_drbg);
71  mbedtls_entropy_free(&entropy);
72 
73  if (status != 0)
74  return -1;
75 #endif
76 #endif
77  return 0;
78 }
79 
80 int winpr_RAND_pseudo(void* output, size_t len)
81 {
82  return winpr_RAND(output, len);
83 }