feat(two-factor): Enhance recovery code generation in TotpTwoFactorService

- Updated recovery code generation to use 12 bytes for base64 conversion, ensuring sufficient characters.
- Implemented fallback padding to guarantee a minimum length of 8 characters for generated codes.
- Adjusted formatting to maintain readability with XXXX-XXXX structure.
This commit is contained in:
Ho Ngoc Hai
2026-01-13 19:01:15 +07:00
parent a25c9f4ad5
commit 7d4958ec92

View File

@@ -102,19 +102,30 @@ public class TotpTwoFactorService : ITwoFactorService
for (int i = 0; i < count; i++)
{
// EN: Generate 8 character alphanumeric recovery code
// VI: Tạo mã khôi phục 8 ký tự chữ và số
var bytes = RandomNumberGenerator.GetBytes(6);
// EN: Generate 12 bytes to ensure enough characters after base64 conversion
// VI: Tạo 12 bytes để đảm bảo đủ ký tự sau khi chuyển đổi base64
var bytes = RandomNumberGenerator.GetBytes(12);
var code = Convert.ToBase64String(bytes)
.Replace("+", "")
.Replace("/", "")
.Replace("+", "X")
.Replace("/", "Y")
.Replace("=", "")
.Substring(0, 8)
.ToUpperInvariant();
// EN: Format as XXXX-XXXX for readability
// VI: Format thành XXXX-XXXX để dễ đọc
codes.Add($"{code.Substring(0, 4)}-{code.Substring(4, 4)}");
// EN: Take first 8 characters, ensure we have enough
// VI: Lấy 8 ký tự đầu tiên, đảm bảo có đủ
if (code.Length >= 8)
{
// EN: Format as XXXX-XXXX for readability
// VI: Format thành XXXX-XXXX để dễ đọc
codes.Add($"{code.Substring(0, 4)}-{code.Substring(4, 4)}");
}
else
{
// EN: Fallback - pad if necessary
// VI: Fallback - pad nếu cần
code = code.PadRight(8, 'Z');
codes.Add($"{code.Substring(0, 4)}-{code.Substring(4, 4)}");
}
}
return codes;