add windows randombytes implementation

backport zeromq/libzmq#1619
This commit is contained in:
Min RK 2016-01-18 10:39:37 +01:00
parent 56835bc833
commit f13d4f1d04
4 changed files with 61 additions and 26 deletions

View File

@ -26,6 +26,7 @@ if(WITH_TWEETNACL)
tweetnacl/src/tweetnacl.c
)
if(WIN32)
list(APPEND TWEETNACL_SOURCES tweetnacl/contrib/randombytes/winrandom.c)
else()
list(APPEND TWEETNACL_SOURCES tweetnacl/contrib/randombytes/devurandom.c)
endif()

View File

@ -1,25 +0,0 @@
/*
randombytes/devurandom.h version 20080713
D. J. Bernstein
Public domain.
*/
#ifndef randombytes_devurandom_H
#define randombytes_devurandom_H
#ifdef __cplusplus
extern "C" {
#endif
extern void randombytes(unsigned char *,unsigned long long);
extern int randombytes_close(void);
#ifdef __cplusplus
}
#endif
#ifndef randombytes_implementation
#define randombytes_implementation "devurandom"
#endif
#endif

View File

@ -1,5 +1,21 @@
/*
randombytes/randombytes.h version 20080713
D. J. Bernstein
Public domain.
*/
#ifndef randombytes_H
#define randombytes_H
#include "devurandom.h"
#ifdef __cplusplus
extern "C" {
#endif
extern void randombytes(unsigned char *,unsigned long long);
extern int randombytes_close(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,43 @@
#include <windows.h>
#include <WinCrypt.h>
#define NCP ((HCRYPTPROV) 0)
HCRYPTPROV hProvider = NCP;
void randombytes(unsigned char *x,unsigned long long xlen)
{
unsigned i;
BOOL ret;
if (hProvider == NCP) {
for(;;) {
ret = CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
if (ret != FALSE) break;
Sleep(1);
}
}
while (xlen > 0) {
if (xlen < 1048576) i = (unsigned) xlen; else i = 1048576;
ret = CryptGenRandom(hProvider, i, x);
if (ret != FALSE) {
Sleep(1);
continue;
}
x += i;
xlen -= i;
}
}
int randombytes_close(void)
{
int rc = -1;
if((hProvider != NCP) && (CryptReleaseContext(hProvider, 0) != FALSE)) {
hProvider = NCP;
rc = 0;
}
return rc;
}