/* * Portable C interface for the system uniform pseudo random * generator. * * Copyright (c) 2009 Manlio Perillo (manlio.perillo@gmail.com) * */ #if defined (HAVE_URANDOM) #include #include #include /* * NOTE: this file descriptor is never explicitly closed. * Instead, the operating system will close it when the process * terminates. */ static int fdUrandom = 0; int hsUrandom(unsigned char* buf, int num) { int n = 0; if (fdUrandom == 0) { fdUrandom = open("/dev/urandom", O_RDONLY); if (fdUrandom == -1) { return -1; } } n = read(fdUrandom, buf, num); /* * TODO: handle the case when less data then requested is read. * TODO: handle EINTR. */ if (n != num) { return -1; } return 0; } #elif defined (HAVE_SSL) #include int hsUrandom(unsigned char* buf, int num) { return RAND_pseudo_bytes(buf, num); } #elif defined (HAVE_WIN32_CRYPT) #include #include /* * This handle is never explicitly released. * Instead, the operating system will release it when the process * terminates. */ static HCRYPTPROV hCryptProv = 0; int hsUrandom(unsigned char* buf, int num) { if (hCryptProv == 0) { if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { return -1; } } if (!CryptGenRandom(hCryptProv, num, buf)) { return -1; } return 0; } #else #error "no suitable source of random data available" #endif