Skip to content

Instantly share code, notes, and snippets.

@iksarfo
Created April 19, 2013 14:27
Show Gist options
  • Save iksarfo/5420710 to your computer and use it in GitHub Desktop.
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
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;
}
}
}
}
}
@DinisCruz
Copy link

here is this code converted to a C# REPL script:

https://gist.github.com/DinisCruz/5420818

@DinisCruz
Copy link

And here it is on the web REPL; http://csharp-repl.apphb.com/37

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment