From 29e443ed762c1c1b01a70aafb3b0b6a05dc376f9 Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Fri, 14 Aug 2020 10:08:50 -0400 Subject: [PATCH] base64 url encode/decode heleprs (#1038) --- src/Core/Services/TokenService.cs | 28 +------------------------ src/Core/Utilities/CoreHelpers.cs | 35 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/src/Core/Services/TokenService.cs b/src/Core/Services/TokenService.cs index 3bfb8999f..82dfdf3ea 100644 --- a/src/Core/Services/TokenService.cs +++ b/src/Core/Services/TokenService.cs @@ -134,7 +134,7 @@ namespace Bit.Core.Services { throw new InvalidOperationException("JWT must have 3 parts."); } - var decodedBytes = Base64UrlDecode(parts[1]); + var decodedBytes = CoreHelpers.Base64UrlDecode(parts[1]); if (decodedBytes == null || decodedBytes.Length < 1) { throw new InvalidOperationException("Cannot decode the token."); @@ -230,32 +230,6 @@ namespace Bit.Core.Services return decoded["iss"].Value(); } - private byte[] Base64UrlDecode(string input) - { - var output = input; - // 62nd char of encoding - output = output.Replace('-', '+'); - // 63rd char of encoding - output = output.Replace('_', '/'); - // Pad with trailing '='s - switch (output.Length % 4) - { - case 0: - // No pad chars in this case - break; - case 2: - // Two pad chars - output += "=="; break; - case 3: - // One pad char - output += "="; break; - default: - throw new InvalidOperationException("Illegal base64url string!"); - } - // Standard base64 decoder - return Convert.FromBase64String(output); - } - private async Task SkipTokenStorage() { var timeout = await _storageService.GetAsync(Constants.VaultTimeoutKey); diff --git a/src/Core/Utilities/CoreHelpers.cs b/src/Core/Utilities/CoreHelpers.cs index c4b1c7f78..45e88d303 100644 --- a/src/Core/Utilities/CoreHelpers.cs +++ b/src/Core/Utilities/CoreHelpers.cs @@ -209,5 +209,40 @@ namespace Bit.Core.Utilities } return JsonConvert.DeserializeObject(json, jsonSerializationSettings); } + + public static string Base64UrlEncode(byte[] input) + { + var output = Convert.ToBase64String(input) + .Replace('+', '-') + .Replace('/', '_') + .Replace("=", string.Empty); + return output; + } + + public static byte[] Base64UrlDecode(string input) + { + var output = input; + // 62nd char of encoding + output = output.Replace('-', '+'); + // 63rd char of encoding + output = output.Replace('_', '/'); + // Pad with trailing '='s + switch (output.Length % 4) + { + case 0: + // No pad chars in this case + break; + case 2: + // Two pad chars + output += "=="; break; + case 3: + // One pad char + output += "="; break; + default: + throw new InvalidOperationException("Illegal base64url string!"); + } + // Standard base64 decoder + return Convert.FromBase64String(output); + } } }