Skip to content

Commit 86ef84f

Browse files
committed
+ Adding CryptoRandom.cs
1 parent 60e1abf commit 86ef84f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Authorize.NET/Utility/CryptoRandom.cs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Security.Cryptography;
6+
7+
namespace AuthorizeNet
8+
{
9+
/// <summary>
10+
/// Source Code from MSDN article http://msdn.microsoft.com/en-us/magazine/cc163367.aspx
11+
/// </summary>
12+
public class CryptoRandom
13+
{
14+
private RNGCryptoServiceProvider _rng =
15+
new RNGCryptoServiceProvider();
16+
private byte[] _uint32Buffer = new byte[4];
17+
18+
public CryptoRandom() { }
19+
public CryptoRandom(Int32 ignoredSeed) { }
20+
21+
public Int32 Next()
22+
{
23+
_rng.GetBytes(_uint32Buffer);
24+
return BitConverter.ToInt32(_uint32Buffer, 0) & 0x7FFFFFFF;
25+
}
26+
27+
public Int32 Next(Int32 maxValue)
28+
{
29+
if (maxValue < 0)
30+
throw new ArgumentOutOfRangeException("maxValue");
31+
return Next(0, maxValue);
32+
}
33+
34+
public Int32 Next(Int32 minValue, Int32 maxValue)
35+
{
36+
if (minValue > maxValue)
37+
throw new ArgumentOutOfRangeException("minValue");
38+
if (minValue == maxValue) return minValue;
39+
Int64 diff = maxValue - minValue;
40+
while (true)
41+
{
42+
_rng.GetBytes(_uint32Buffer);
43+
UInt32 rand = BitConverter.ToUInt32(_uint32Buffer, 0);
44+
45+
Int64 max = (1 + (Int64)UInt32.MaxValue);
46+
Int64 remainder = max % diff;
47+
if (rand < max - remainder)
48+
{
49+
return (Int32)(minValue + (rand % diff));
50+
}
51+
}
52+
}
53+
54+
public double NextDouble()
55+
{
56+
_rng.GetBytes(_uint32Buffer);
57+
UInt32 rand = BitConverter.ToUInt32(_uint32Buffer, 0);
58+
return rand / (1.0 + UInt32.MaxValue);
59+
}
60+
61+
public void NextBytes(byte[] buffer)
62+
{
63+
if (buffer == null) throw new ArgumentNullException("buffer");
64+
_rng.GetBytes(buffer);
65+
}
66+
}
67+
}

0 commit comments

Comments
 (0)