sharp-chat/SharpChat.Common/RNG.cs

43 lines
1.3 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using System;
using System.Security.Cryptography;
2022-08-30 15:05:29 +00:00
using System.Text;
2022-08-30 15:00:58 +00:00
namespace SharpChat {
public static class RNG {
2022-08-30 15:05:29 +00:00
private static object Lock { get; } = new();
private static Random NormalRandom { get; } = new();
2022-08-30 15:00:58 +00:00
private static RandomNumberGenerator SecureRandom { get; } = RandomNumberGenerator.Create();
public static int Next() {
lock (Lock)
return NormalRandom.Next();
}
public static int Next(int max) {
lock (Lock)
return NormalRandom.Next(max);
}
public static int Next(int min, int max) {
lock (Lock)
return NormalRandom.Next(min, max);
}
public static void NextBytes(byte[] buffer) {
lock(Lock)
SecureRandom.GetBytes(buffer);
}
2022-08-30 15:05:29 +00:00
public const string ID_CHARS = @"abcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string NextString(int length, string chars = ID_CHARS) {
byte[] buffer = new byte[length];
NextBytes(buffer);
StringBuilder sb = new();
foreach(byte b in buffer)
sb.Append(chars[b % chars.Length]);
return sb.ToString();
}
2022-08-30 15:00:58 +00:00
}
}