Skip to main content

Validates whether or not a string is Base64 encoded.

/// <summary>
/// Optimized method for validating Base64-encoded strings.
/// </summary>
/// <param name="value">The string to validate as Base64-encoded.</param>
/// <returns>True if the string is a valid Base64-encoded string; otherwise, false.</returns>
private static bool IsBase64EncodedString(string value)
{
    if (string.IsNullOrWhiteSpace(value) || value.Length % 4 != 0)
    {
        return false;
    }

    // Use stackalloc for small strings, heap allocation for larger ones
    Span<byte> buffer = value.Length <= 256
        ? stackalloc byte[value.Length]
        : new byte[value.Length];

    // Convert string to UTF-8 bytes (more efficient than ASCII conversion)
    var bytesWritten = System.Text.Encoding.UTF8.GetBytes(value, buffer);

    // Calculate exact output size needed
    var outputSize = System.Buffers.Text.Base64.GetMaxDecodedFromUtf8Length(bytesWritten);
    Span<byte> output = outputSize <= 256
        ? stackalloc byte[outputSize]
        : new byte[outputSize];

    // Attempt to decode - this validates format automatically
    return System.Buffers.Text.Base64.DecodeFromUtf8(
        buffer[..bytesWritten],
        output,
        out _,
        out _) == System.Buffers.OperationStatus.Done;
}