Last active
March 5, 2020 11:03
-
-
Save nathanchere/f29801c479ad08362124b511ac4c79e0 to your computer and use it in GitHub Desktop.
LUID - Locally unique identifier
This file contains hidden or 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.Security.Cryptography; | |
using System.Text; | |
namespace TrotenLib | |
{ | |
/// <summary> | |
/// Generate unique-enough pseudo-random identifiers where GUID is for some reason unsuitable | |
/// Explanation: https://stackoverflow.com/a/37099588/243557 | |
/// </summary> | |
public static class LUID | |
{ | |
private static readonly RNGCryptoServiceProvider RandomGenerator = new RNGCryptoServiceProvider(); | |
private static readonly char[] ValidCharacters = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".ToCharArray(); | |
public const int DefaultLength = 6; | |
private static int counter = 0; | |
public static string Generate(int length = DefaultLength) | |
{ | |
var randomData = new byte[length]; | |
RandomGenerator.GetNonZeroBytes(randomData); | |
var result = new StringBuilder(DefaultLength); | |
foreach (var value in randomData) | |
{ | |
counter = (counter + value) % (ValidCharacters.Length - 1); | |
result.Append(ValidCharacters[counter]); | |
} | |
return result.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment