mirror of
https://github.com/C9Glax/tranga.git
synced 2025-02-23 07:40:13 +01:00
39 lines
1.3 KiB
C#
39 lines
1.3 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace API;
|
|
|
|
public static class TokenGen
|
|
{
|
|
private const int MinimumLength = 32;
|
|
private const int MaximumLength = 64;
|
|
private const string Chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
|
|
public static string CreateToken(Type t, string identifier) => CreateToken(t.Name, identifier);
|
|
|
|
public static string CreateToken(string prefix, string identifier)
|
|
{
|
|
|
|
|
|
if (prefix.Length + 1 >= MaximumLength - MinimumLength)
|
|
throw new ArgumentException("Prefix to long to create Token of meaningful length.");
|
|
|
|
int tokenLength = MaximumLength - prefix.Length - 1;
|
|
|
|
if (string.IsNullOrWhiteSpace(identifier))
|
|
{
|
|
// No identifier, just create a random token
|
|
byte[] rng = new byte[tokenLength];
|
|
RandomNumberGenerator.Create().GetBytes(rng);
|
|
string key = new(rng.Select(b => Chars[b % Chars.Length]).ToArray());
|
|
key = string.Join('-', prefix, key);
|
|
return key;
|
|
}
|
|
|
|
// Identifier provided, create a token based on the identifier hashed
|
|
byte[] hash = MD5.HashData(Encoding.UTF8.GetBytes(identifier));
|
|
string token = Convert.ToHexStringLower(hash);
|
|
|
|
return string.Join('-', prefix, token);
|
|
}
|
|
} |