Skip to content

Instantly share code, notes, and snippets.

@enif-lee
Created October 8, 2019 03:17
Show Gist options
  • Save enif-lee/b9e581291f4968cb2fb1bf3819294eb7 to your computer and use it in GitHub Desktop.
Save enif-lee/b9e581291f4968cb2fb1bf3819294eb7 to your computer and use it in GitHub Desktop.
C# Safe Base64 Helper with c# 8
public static class Base64Helper
{
/// <summary>
/// Convert to url safe base 64
/// </summary>
/// <param name="base64">base64 string</param>
/// <returns></returns>
public static string ToSafeBase64(string base64)
{
return base64
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
/// <summary>
/// Reverse origin base 64 from url safe base 64
/// </summary>
/// <param name="safe64">url safe base 64</param>
/// <returns></returns>
public static string FromSafeBase64(string safe64)
{
return safe64
.Replace('-', '+')
.Replace('_', '/')
+
(safe64.Length % 4) switch
{
2 => "==",
3 => "="
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment