From 281ae3c3458bf022a659b04e0f269c0f0d21d34b Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 12 Apr 2022 20:52:16 +0800 Subject: ... --- BackEnd/Timeline/Configs/TokenOptions.cs | 5 ++--- .../Services/Token/SecureRandomUserTokenService.cs | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/BackEnd/Timeline/Configs/TokenOptions.cs b/BackEnd/Timeline/Configs/TokenOptions.cs index d8e968c7..d643c3d2 100644 --- a/BackEnd/Timeline/Configs/TokenOptions.cs +++ b/BackEnd/Timeline/Configs/TokenOptions.cs @@ -3,9 +3,8 @@ public class TokenOptions { /// - /// The length of the generated secure random token counted in byte. - /// Note the byte will be converted to hex form when used. - /// Default is 32 byte long. + /// The length of the token. + /// Default is 16. /// public long? TokenLength { get; set; } } diff --git a/BackEnd/Timeline/Services/Token/SecureRandomUserTokenService.cs b/BackEnd/Timeline/Services/Token/SecureRandomUserTokenService.cs index 2ab263de..4d79295a 100644 --- a/BackEnd/Timeline/Services/Token/SecureRandomUserTokenService.cs +++ b/BackEnd/Timeline/Services/Token/SecureRandomUserTokenService.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; +using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -33,13 +34,23 @@ namespace Timeline.Services.Token _secureRandom.Dispose(); } + private static readonly char[] AlphaDigitString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); + private string GenerateSecureRandomTokenString() { var option = _optionMonitor.CurrentValue; - var tokenLength = option.TokenLength ?? 32; + var tokenLength = option.TokenLength ?? 16; var buffer = new byte[tokenLength]; _secureRandom.GetBytes(buffer); - return Convert.ToHexString(buffer); + + StringBuilder stringBuilder = new(); + + foreach (byte b in buffer) + { + stringBuilder.Append(AlphaDigitString[b % AlphaDigitString.Length]); + } + + return stringBuilder.ToString(); } /// -- cgit v1.2.3