Project 'andrew.cornell/nfa-pruning-analysis' was moved to 'katherine.cornell/nfa-pruning-analysis'. Please update any links and bookmarks that may still have the old path.
Select Git revision
-
Andrew Cornell authoredAndrew Cornell authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
RandomHelper.cs 1.18 KiB
using System.Security.Cryptography;
using System.Text;
namespace Coscine.Database.Util
{
public class RandomHelper
{
const string humanSafeChars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const string urlSafeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
const char separatorChar = '-';
static readonly RandomNumberGenerator rng = RandomNumberGenerator.Create();
public static string GenerateRandomChunk(int length, int chunks = 1, bool humanSafe = false)
{
char[] chars = (humanSafe ? humanSafeChars : urlSafeChars).ToCharArray();
byte[] randomBytes = new byte[chunks * length];
lock (rng)
{
rng.GetBytes(randomBytes);
}
StringBuilder code = new StringBuilder();
for (int i = 0; i < randomBytes.Length; i++)
{
if (i % length == 0)
{
code.Append(separatorChar);
}
code.Append(chars[randomBytes[i] % chars.Length]);
}
code.Remove(0, 1);
return code.ToString();
}
}
}