sockscape/server_old/Libraries/Glove/RandomContext.cs

77 lines
2.1 KiB
C#
Raw Normal View History

2017-05-17 21:06:16 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
2017-08-22 20:59:41 +00:00
using System.Security.Cryptography;
2017-05-17 21:06:16 +00:00
2017-07-22 19:27:41 +00:00
namespace Glove {
public static class RNG {
2017-08-21 21:03:32 +00:00
private static readonly Random RandCtx = new Random();
2017-08-22 20:59:41 +00:00
private static readonly RNGCryptoServiceProvider CsRandCtx
= new RNGCryptoServiceProvider();
2017-05-17 21:06:16 +00:00
public static int Next() {
lock(RandCtx) {
return RandCtx.Next();
}
}
public static int Next(int maxValue) {
lock(RandCtx) {
return RandCtx.Next(maxValue);
}
}
public static int Next(int minValue, int maxValue) {
lock(RandCtx) {
return RandCtx.Next(minValue, maxValue);
}
}
public static double NextDouble() {
lock(RandCtx) {
return RandCtx.NextDouble();
}
}
public static void NextBytes(byte[] buffer) {
lock(RandCtx) {
RandCtx.NextBytes(buffer);
}
}
public static byte[] NextBytes(int length) {
2017-08-22 20:59:41 +00:00
lock(CsRandCtx) {
2017-05-17 21:06:16 +00:00
var buffer = new byte[length];
2017-08-22 20:59:41 +00:00
CsRandCtx.GetNonZeroBytes(buffer);
2017-05-17 21:06:16 +00:00
return buffer;
}
}
public static BigInteger NextPrime(int byteCount) {
var bytes = new byte[byteCount];
BigInteger prime;
do {
NextBytes(bytes);
prime = BigInteger.Abs(new BigInteger(bytes)) | 1;
} while(!prime.IsProbablePrime());
return prime;
}
public static BigInteger NextBigInt(BigInteger minValue, BigInteger maxValue) {
var byteCount = maxValue.ToByteArray().Length;
var randomNumber = BigInteger.Abs(new BigInteger(NextBytes(byteCount)));
var delta = maxValue - minValue + 1;
return minValue + (randomNumber % delta);
}
2017-05-20 23:33:39 +00:00
public static BigInteger NextBigInt(int byteCount)
=> BigInteger.Abs(new BigInteger(NextBytes(byteCount)));
2017-05-17 21:06:16 +00:00
}
}