Created
April 19, 2013 14:27
-
-
Save iksarfo/5420710 to your computer and use it in GitHub Desktop.
TeamMentor requires a stronger random number generator https://github.com/TeamMentor/Master/issues/258
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Security.Cryptography; | |
using System.Threading.Tasks; | |
namespace Wimiro.Spike.RNGCryptoGuid { | |
class Program { | |
static void Main(string[] args) | |
{ | |
var watch = Stopwatch.StartNew(); | |
Task.Run(() => RunGuidCreation(watch)); | |
Task.Run(() => RunCryptoGuidCreation(watch)); | |
Console.ReadLine(); | |
} | |
private static void RunGuidCreation(Stopwatch watch) | |
{ | |
var guids = new List<Guid>(); | |
for (var i = 0; i < 10000000; i++) | |
{ | |
guids.Add(Guid.NewGuid()); | |
} | |
Console.WriteLine("RunGuidCreation: " + string.Format("{0:n0}", watch.ElapsedMilliseconds)); | |
} | |
private static void RunCryptoGuidCreation(Stopwatch watch) { | |
var guids = new List<Guid>(); | |
for (var i = 0; i < 10000000; i++) { | |
guids.Add(CSPRNG.GetGuid()); | |
} | |
Console.WriteLine("RunCryptoGuidCreation: " + string.Format("{0:n0}", watch.ElapsedMilliseconds)); | |
} | |
public static class CSPRNG { | |
public static byte[] GetBytes(int entropy) { | |
if (entropy < 8) { | |
throw new ArgumentOutOfRangeException("entropy", | |
"Entropy must be 64 bits or greater to be cryptographically secure."); | |
} | |
using (RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider()) { | |
byte[] _obj = new byte[entropy]; | |
_rng.GetBytes(_obj); | |
return _obj; | |
} | |
} | |
public static Guid GetGuid() { | |
using (RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider()) { | |
byte[] _obj = new byte[16]; | |
_rng.GetBytes(_obj); | |
return new Guid(_obj); | |
} | |
} | |
public static long GetInt64(bool allowNegativeValue = false) { | |
using (RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider()) { | |
byte[] _obj = new byte[8]; | |
_rng.GetBytes(_obj); | |
long _num = BitConverter.ToInt64(_obj, 0); | |
if (!allowNegativeValue) { | |
_num = (_num & ~(1L << 63)); | |
} | |
return _num; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
here is this code converted to a C# REPL script:
https://gist.github.com/DinisCruz/5420818