winrandom.c 794 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#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);
25
    if (ret == FALSE) {
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
      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;
}