Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit c2f3313

Browse files
committed
Add useful ToBase64UrlSafe/FromBase64UrlSafe from JWT spec
1 parent 1f03e7f commit c2f3313

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/ServiceStack.Text/StringExtensions.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,33 @@ public static byte[] ToUtf8Bytes(this double doubleVal)
321321
return FastToUtf8Bytes(doubleStr);
322322
}
323323

324+
// from JWT spec
325+
public static string ToBase64UrlSafe(this byte[] input)
326+
{
327+
var output = Convert.ToBase64String(input);
328+
output = output.Split('=')[0]; // Remove any trailing '='s
329+
output = output.Replace('+', '-'); // 62nd char of encoding
330+
output = output.Replace('/', '_'); // 63rd char of encoding
331+
return output;
332+
}
333+
334+
// from JWT spec
335+
public static byte[] FromBase64UrlSafe(this string input)
336+
{
337+
var output = input;
338+
output = output.Replace('-', '+'); // 62nd char of encoding
339+
output = output.Replace('_', '/'); // 63rd char of encoding
340+
switch (output.Length % 4) // Pad with trailing '='s
341+
{
342+
case 0: break; // No pad chars in this case
343+
case 2: output += "=="; break; // Two pad chars
344+
case 3: output += "="; break; // One pad char
345+
default: throw new Exception("Illegal base64url string!");
346+
}
347+
var converted = Convert.FromBase64String(output); // Standard base64 decoder
348+
return converted;
349+
}
350+
324351
/// <summary>
325352
/// Skip the encoding process for 'safe strings'
326353
/// </summary>

0 commit comments

Comments
 (0)