[postgres-Server-V2] feat: Convert chapterNumeber to string

This commit is contained in:
Alessandro Benetton
2025-01-25 11:57:54 +01:00
parent be6b3da1be
commit ebe7e145aa
31 changed files with 881 additions and 430 deletions

View File

@ -5,36 +5,35 @@ namespace API;
public static class TokenGen
{
private const uint MinimumLength = 8;
private const int MinimumLength = 32;
private const int MaximumLength = 64;
private const string Chars = "abcdefghijklmnopqrstuvwxyz0123456789";
public static string CreateToken(Type t, uint fullLength) => CreateToken(t.Name, fullLength);
public static string CreateToken(Type t, string identifier) => CreateToken(t.Name, identifier);
public static string CreateToken(string prefix, uint fullLength)
public static string CreateToken(string prefix, string identifier)
{
if (prefix.Length + 1 >= fullLength - MinimumLength)
if (prefix.Length + 1 >= MaximumLength - MinimumLength)
throw new ArgumentException("Prefix to long to create Token of meaningful length.");
long l = fullLength - prefix.Length - 1;
byte[] rng = new byte[l];
RandomNumberGenerator.Create().GetBytes(rng);
string key = new (rng.Select(b => Chars[b % Chars.Length]).ToArray());
key = string.Join('-', prefix, key);
return key;
}
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;
}
public static string CreateTokenHash(string prefix, uint fullLength, string[] keys)
{
if (prefix.Length + 1 >= fullLength - MinimumLength)
throw new ArgumentException("Prefix to long to create Token of meaningful length.");
int l = (int)(fullLength - prefix.Length - 1);
MD5 md5 = MD5.Create();
byte[][] hashes = keys.Select(key => md5.ComputeHash(Encoding.UTF8.GetBytes(key))).ToArray();
byte[] xOrHash = new byte[l];
foreach (byte[] hash in hashes)
for(int i = 0; i < hash.Length; i++)
xOrHash[i] = (byte)(xOrHash[i] ^ (i >= hash.Length ? 0 : hash[i]));
string key = new (xOrHash.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);
}
}