Skip to content

Commit d2ec017

Browse files
committed
Small tweak to CryptoRandom's SanityCheck.
1 parent 8901163 commit d2ec017

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

CryptoRandom.cs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,20 @@ public CryptoRandom() : base(Seed: 0)
3232

3333
static void SanityCheck()
3434
{
35-
var testBuffer = new byte[BYTE_CACHE_SIZE];
35+
var testBuffer = new byte[BYTE_CACHE_SIZE / 2];
3636
int status, i, j;
37+
const int COLLISION_FREE_BLOCK_SIZE = 16;
3738

38-
status = (int)BCrypt.BCryptGenRandom(testBuffer, BYTE_CACHE_SIZE / 2);
39+
status = (int)BCrypt.BCryptGenRandom(testBuffer, testBuffer.Length);
3940
if (status != (int)BCrypt.NTSTATUS.STATUS_SUCCESS) throw new CryptographicException(status);
4041

41-
for (i = BYTE_CACHE_SIZE / 2; i < BYTE_CACHE_SIZE; ++i)
42-
if (testBuffer[i] != 0) throw new CryptographicException("CryptoRandom failed sanity check #1.");
43-
44-
for (i = 0, status = 0, j = BYTE_CACHE_SIZE / 2; i < j; ++i) status |= testBuffer[i];
45-
if (status == 0) throw new CryptographicException("CryptoRandom failed sanity check #2.");
42+
if (testBuffer.Length < COLLISION_FREE_BLOCK_SIZE * 2) return; // should be compiled away
43+
for (i = 0; i < testBuffer.Length - COLLISION_FREE_BLOCK_SIZE; i += COLLISION_FREE_BLOCK_SIZE)
44+
{
45+
for (j = 0, status = 0; j < COLLISION_FREE_BLOCK_SIZE; ++j)
46+
status |= testBuffer[i + j] ^ testBuffer[i + j + COLLISION_FREE_BLOCK_SIZE];
47+
if (status == 0) throw new CryptographicException("CryptoRandom failed sanity check #2.");
48+
}
4649
}// SanityCheck()
4750

4851
#region NextLong()

0 commit comments

Comments
 (0)