Tranga/API/TokenGen.cs

39 lines
1.4 KiB
C#
Raw Normal View History

2024-12-14 21:53:29 +01:00
using System.Security.Cryptography;
using System.Text;
2024-12-14 21:53:29 +01:00
namespace API;
public static class TokenGen
{
private const int MinimumLength = 32;
private const int MaximumLength = 64;
2024-12-14 21:53:29 +01:00
private const string Chars = "abcdefghijklmnopqrstuvwxyz0123456789";
public static string CreateToken(Type t, params string[] identifiers) => CreateToken(t.Name, identifiers);
2024-12-14 21:53:29 +01:00
public static string CreateToken(string prefix, params string[] identifiers)
2024-12-14 21:53:29 +01:00
{
if (prefix.Length + 1 >= MaximumLength - MinimumLength)
2024-12-14 21:53:29 +01:00
throw new ArgumentException("Prefix to long to create Token of meaningful length.");
int tokenLength = MaximumLength - prefix.Length - 1;
if (identifiers.Length == 0)
{
// 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(string.Join("", identifiers)));
string token = Convert.ToHexStringLower(hash);
return string.Join('-', prefix, token);
}
2024-12-14 21:53:29 +01:00
}