ggentropy.c (1907B)
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 <stdbool.h> 36 #include <stddef.h> 37 #include <assert.h> 38 39 #if PLATFORM_WINDOWS 40 41 #pragma comment( lib, "bcrypt.lib" ) 42 43 #define WIN32_LEAN_AND_MEAN 44 #include <windows.h> 45 #include <bcrypt.h> 46 47 bool ggentropy( void * buf, size_t n ) { 48 assert( n <= 256 ); 49 return !FAILED( BCryptGenRandom( NULL, ( PUCHAR ) buf, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ); 50 } 51 52 #elif PLATFORM_LINUX 53 54 #include <unistd.h> 55 #include <sys/syscall.h> 56 57 bool ggentropy( void * buf, size_t n ) { 58 assert( n <= 256 ); 59 int ok = syscall( SYS_getrandom, buf, n, 0 ); 60 return ok >= 0 && ( size_t ) ok == n; 61 } 62 63 #elif PLATFORM_HAS_ARC4RANDOM 64 65 #include <stdlib.h> 66 67 bool ggentropy( void * buf, size_t n ) { 68 assert( n <= 256 ); 69 arc4random_buf( buf, n ); 70 return true; 71 } 72 73 #else 74 #error new platform 75 #endif