Move util_ files into utils directory, move main.cpp into src
[gssweb.git] / json_gssapi / src / utils / util_random.cpp
1 /*
2  * Copyright (c) 2014 <copyright holder> <email>
3  *
4  * For license details, see the LICENSE file in the root of this project.
5  *
6  */
7
8 #include "util_random.h"
9
10 #ifdef WIN32
11 #include <random>
12 #endif
13 #ifdef HAVE_OPENSSL
14 #include <openssl/err.h>
15 #include <openssl/rand.h>
16 #endif
17
18
19 bool randGenPseudoRandom(unsigned char *buffer, size_t len)
20 {
21 #ifdef WIN32
22   std::random_device rd;   // slow; use to seed only!
23   std::mt19937 gen(rd());  // seed mersenne twister.
24   std::uniform_int_distribution<> dist(0,UCHAR_MAX);
25   for (size_t i=0; i<len; i++)
26     buffer[i] = dist(gen);
27   return true;
28 #elif defined(HAVE_OPENSSL)
29   int  osslReturn = 0;
30   bool existingErrors = false;
31
32   /* Error checking */
33   // See if there are any queued OpenSSL errors already.
34   existingErrors = ( 0 == ERR_peek_error() );
35
36   /* Setup          */
37   /* Main           */
38   // Generate random byte string
39   osslReturn = RAND_pseudo_bytes(buffer, len);
40
41   // Discard the error message if there weren't any OpenSSL errors to begin with.
42   if (osslReturn == 1 && !existingErrors)
43   {
44     while (0 != ERR_get_error() );
45     return(false);
46   }
47   return true;
48 #else
49   #error no pseudo random generator available
50 #endif
51 }
52