base64 url encode/decode heleprs (#1038)

This commit is contained in:
Kyle Spearrin 2020-08-14 10:08:50 -04:00 committed by GitHub
parent f95cddd05a
commit 29e443ed76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 27 deletions

View File

@ -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<string>();
}
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<bool> SkipTokenStorage()
{
var timeout = await _storageService.GetAsync<int?>(Constants.VaultTimeoutKey);

View File

@ -209,5 +209,40 @@ namespace Bit.Core.Utilities
}
return JsonConvert.DeserializeObject<T>(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);
}
}
}