Update Base64 Encoders to deal with suffixes (#284)

* Update Base64 Encoders to deal with suffixes

* Set UriDataEscape to public for unit tests
This commit is contained in:
Thomas Boop
2020-01-27 21:38:31 -05:00
committed by Tingluo Huang
parent b676ab3d33
commit c45aebc9ab
3 changed files with 43 additions and 7 deletions

View File

@@ -16,6 +16,11 @@ namespace GitHub.DistributedTask.Logging
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
public static String Base64StringEscapeTrimmed(String value)
{
return TrimBase64End(Convert.ToBase64String(Encoding.UTF8.GetBytes(value)));
}
// Base64 is 6 bits -> char
// A byte is 8 bits
@@ -67,15 +72,15 @@ namespace GitHub.DistributedTask.Logging
{
var shiftArray = new byte[bytes.Length - shift];
Array.Copy(bytes, shift, shiftArray, 0, bytes.Length - shift);
return Convert.ToBase64String(shiftArray);
return TrimBase64End(Convert.ToBase64String(shiftArray));
}
else
{
return Convert.ToBase64String(bytes);
return TrimBase64End(Convert.ToBase64String(bytes));
}
}
private static String UriDataEscape(
public static String UriDataEscape(
String value,
Int32 maxSegmentSize)
{
@@ -103,5 +108,26 @@ namespace GitHub.DistributedTask.Logging
return result.ToString();
}
private static String TrimBase64End(String value)
{
if (String.IsNullOrEmpty(value))
{
return String.Empty;
}
if (value.EndsWith('='))
{
var trimmed = value.TrimEnd('=');
if (trimmed.Length > 1)
{
// If a base64 string ends in '=' it indicates that the base 64 character is only using 2 or 4 of the six bytes and will change if another character is added
// For example 'ab' is 'YWI=' in base 64
// 'abc' is 'YWJj'
// We need to detect YW, not YWI so we trim the last character ('I')
return trimmed.Substring(0, trimmed.Length - 1);
}
}
return value;
}
}
}