ggentropy.cpp (1885B)
1 /* 2 * ggentropy v1.0 3 * 4 * Copyright (c) 2021 Michael Savage <mike@mikejsavage.co.uk> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #if defined( _WIN32 ) 20 # define PLATFORM_WINDOWS 1 21 22 #elif defined( __linux__ ) 23 # define PLATFORM_LINUX 1 24 25 #elif defined( __APPLE__ ) 26 # define PLATFORM_HAS_ARC4RANDOM 1 27 28 #elif defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __NetBSD__ ) 29 # define PLATFORM_HAS_ARC4RANDOM 1 30 31 #else 32 # error new platform 33 #endif 34 35 #include <stddef.h> 36 #include <assert.h> 37 38 #if PLATFORM_WINDOWS 39 40 #pragma comment( lib, "bcrypt.lib" ) 41 42 #define WIN32_LEAN_AND_MEAN 43 #include <windows.h> 44 #include <bcrypt.h> 45 46 bool ggentropy( void * buf, size_t n ) { 47 assert( n <= 256 ); 48 return !FAILED( BCryptGenRandom( NULL, ( PUCHAR ) buf, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ); 49 } 50 51 #elif PLATFORM_LINUX 52 53 #include <unistd.h> 54 #include <sys/syscall.h> 55 56 bool ggentropy( void * buf, size_t n ) { 57 assert( n <= 256 ); 58 int ok = syscall( SYS_getrandom, buf, n, 0 ); 59 return ok >= 0 && size_t( ok ) == n; 60 } 61 62 #elif PLATFORM_HAS_ARC4RANDOM 63 64 #include <stdlib.h> 65 66 bool ggentropy( void * buf, size_t n ) { 67 assert( n <= 256 ); 68 arc4random_buf( buf, n ); 69 return true; 70 } 71 72 #else 73 #error new platform 74 #endif