61 lines
1.2 KiB
C++
61 lines
1.2 KiB
C++
//----------------------------------------------------------------------------
|
|
//
|
|
// Copyright (C) 2006 Intel Corporation
|
|
//
|
|
// File: MyRand.cpp
|
|
//
|
|
// Contents: Defines a windows based object for generating pseudo random
|
|
// numbers.
|
|
//
|
|
//----------------------------------------------------------------------------
|
|
|
|
#include "MyRand.h"
|
|
|
|
MyRand::MyRand()
|
|
{
|
|
_hCryptProv = 0;
|
|
if (!CryptAcquireContext(&_hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
|
|
{
|
|
throw RandomNumberError();
|
|
return;
|
|
}
|
|
}
|
|
|
|
unsigned int MyRand::RandomNumber() const
|
|
{
|
|
unsigned int random = 0;
|
|
unsigned char data[4];
|
|
if(!CryptGenRandom(_hCryptProv, 4, data))
|
|
{
|
|
throw RandomNumberError();
|
|
}
|
|
if (memcpy_s(&random, sizeof(random), data, ARRAYSIZE(data)))
|
|
{
|
|
throw RandomNumberError();
|
|
}
|
|
return random;
|
|
}
|
|
|
|
unsigned char MyRand::RandomByte() const
|
|
{
|
|
unsigned char random = 0;
|
|
unsigned char data[1];
|
|
if(!CryptGenRandom(_hCryptProv, 1, data))
|
|
{
|
|
throw RandomNumberError();
|
|
}
|
|
if (memcpy_s(&random, sizeof(random), data, ARRAYSIZE(data)))
|
|
{
|
|
throw RandomNumberError();
|
|
}
|
|
return random;
|
|
}
|
|
|
|
MyRand::~MyRand()
|
|
{
|
|
if(_hCryptProv != 0)
|
|
{
|
|
CryptReleaseContext(_hCryptProv,0);
|
|
}
|
|
}
|