?? randomgenerator.cpp
字號:
// RandomGenerator.cpp: implementation of the CRandomGenerator class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "RSAUtil.h"
#include "RandomGenerator.h"
#include "BestMDHash.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CRandomGenerator::CRandomGenerator()
{
srand(time(NULL));
m_nUpdateCounter = 0;
}
CRandomGenerator::~CRandomGenerator()
{
SaveSeedIntoFile();
}
BOOL CRandomGenerator::
LoadSeedFromFile(const char* szFileName)
{
m_strFileName = szFileName;
FILE* fp = fopen(m_strFileName, "rb");
if (NULL == fp)
{
return false;
}
fread(m_bySeed, 1, sizeof(m_bySeed), fp);
fclose(fp);
m_nUpdateCounter = 100;
return true;
}
BOOL CRandomGenerator::
SaveSeedIntoFile()
{
FILE* fp;
fp = fopen(m_strFileName, "wb");
if (NULL == fp)
{
return false;
}
fwrite(m_bySeed, 1, sizeof(m_bySeed), fp);
fclose(fp);
return true;
}
void CRandomGenerator::
Update(int n)
{
BYTE by16[16];
GetMDHash(&n, sizeof(n), by16);
n ^= rand();
n %= sizeof(m_bySeed);
for (int i = n; i < n + 16; i++)
{
m_bySeed[i % sizeof(m_bySeed)] ^= by16[i];
}
m_nUpdateCounter++;
if (0 == (m_nUpdateCounter % 1024))
{
SaveSeedIntoFile();
}
for (i = 0; i < sizeof(m_bySeed); i++)
{
m_bySeed[i] ^= rand() % 0xff;
}
return;
}
void CRandomGenerator::
_RandomGetBytesEntropy(unsigned char* buf, unsigned l, unsigned effective)
{
for (unsigned i = 0; i < l; i++)
{
buf[i] = m_bySeed[rand() % sizeof(m_bySeed)];
}
}
/*
* Generate a random bignum of the specified length, with the given
* high and low 8 bits. "High" is merged into the high 8 bits of the
* number. For example, set it to 0x80 to ensure that the number is
* exactly "bits" bits long (i.e. 2^(bits-1) <= bn < 2^bits).
* "Low" is merged into the low 8 bits. For example, set it to
* 1 to ensure that you generate an odd number.
*/
int CRandomGenerator::
GenRand(CBigNumber *bn, unsigned bits, BYTE high, BYTE low, unsigned effective)
{
unsigned char buf[64];
unsigned bytes;
unsigned l;
int err;
bnSetQ(bn, 0);
/* Get high random bits */
bytes = (bits+7) / 8;
l = bytes < sizeof(buf) ? bytes : sizeof(buf);
_RandomGetBytesEntropy(buf, l, effective);
/* Mask off excess high bits */
buf[0] &= 255 >> (-(int)bits & 7);
/* Merge in specified high bits */
buf[0] |= high >> (-(int)bits & 7);
if (bits & 7)
buf[1] |= high << (bits & 7);
for (;;) {
bytes -= l;
if (!bytes) /* Last word - merge in low bits */
buf[l-1] |= low;
err = bnInsertBigBytes(bn, buf, bytes, l);
if (!bytes || err < 0)
break;
l = bytes < sizeof(buf) ? bytes : sizeof(buf);
_RandomGetBytesEntropy(buf, l, 0);
}
/* Burn and return */
return err;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -