1 /* $OpenBSD: getentropy_win.c,v 1.6 2020/11/11 10:41:24 bcook Exp $ */ 2 3 /* 4 * Copyright (c) 2014, Theo de Raadt <deraadt@openbsd.org> 5 * Copyright (c) 2014, Bob Beck <beck@obtuse.com> 6 * 7 * Permission to use, copy, modify, and distribute this software for any 8 * purpose with or without fee is hereby granted, provided that the above 9 * copyright notice and this permission notice appear in all copies. 10 * 11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 18 * 19 * Emulation of getentropy(2) as documented at: 20 * http://man.openbsd.org/getentropy.2 21 */ 22 23 #include <windows.h> 24 #include <bcrypt.h> 25 #include <errno.h> 26 #include <stdint.h> 27 #include <sys/types.h> 28 29 int getentropy(void *buf, size_t len); 30 31 /* 32 * On Windows, BCryptGenRandom with BCRYPT_USE_SYSTEM_PREFERRED_RNG is supposed 33 * to be a well-seeded, cryptographically strong random number generator. 34 * https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom 35 */ 36 int 37 getentropy(void *buf, size_t len) 38 { 39 if (len > 256) { 40 errno = EIO; 41 return (-1); 42 } 43 44 if (FAILED(BCryptGenRandom(NULL, buf, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { 45 errno = EIO; 46 return (-1); 47 } 48 49 return (0); 50 } 51