using System.Text;
namespace Khaemhat.Infrastructure.Security;
/// Base32 of RFC 4648 (alphabet A-Z2-7), used by TOTP secrets and activation codes. No padding is written.
public static class Base32
{
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// Encodes bytes.
/// The bytes.
/// The text, without padding.
public static string Encode(ReadOnlySpan data)
{
var builder = new StringBuilder((data.Length * 8 + 4) / 5);
int buffer = 0, bits = 0;
foreach (var b in data)
{
buffer = (buffer << 8) | b;
bits += 8;
while (bits >= 5)
{
builder.Append(Alphabet[(buffer >> (bits - 5)) & 31]);
bits -= 5;
}
}
if (bits > 0)
{
builder.Append(Alphabet[(buffer << (5 - bits)) & 31]);
}
return builder.ToString();
}
/// Decodes text; spaces, dashes and padding are ignored, letters may be lower-case.
/// The text.
/// The bytes.
/// A character is not in the alphabet.
public static byte[] Decode(string text)
{
ArgumentNullException.ThrowIfNull(text);
var output = new List(text.Length * 5 / 8);
int buffer = 0, bits = 0;
foreach (var raw in text)
{
if (raw is ' ' or '-' or '=')
{
continue;
}
var index = Alphabet.IndexOf(char.ToUpperInvariant(raw), StringComparison.Ordinal);
if (index < 0)
{
throw new FormatException("The text is not valid base32.");
}
buffer = (buffer << 5) | index;
bits += 5;
if (bits >= 8)
{
output.Add((byte)((buffer >> (bits - 8)) & 0xFF));
bits -= 8;
}
}
return [.. output];
}
}