问题
I stumbled upon a strange behavior of Convert.FromBase64String in .NET 4.7.2. Normally it would throw an exception when the padding is not correct. But I found a case where adding another padding character produces an incorrect result instead of an exception.
var correct = Convert.FromBase64String("YWE=");
In this case correct is [97, 97] or "aa" in a string form. But when I add another =:
var incorrect = Convert.FromBase64String("YWE==");
instead of getting an exception I get one byte less and incorrect is [88] or "X" is a string form.
Weird. Is this a bug and it should be reported? Or is it a known/documented behavior? I couldn't find any references to this.
Compare to Ruby. This evaluates to "aa":
Base64.strict_decode64 "YWE="
And this raises an exception:
Base64.strict_decode64 "YWE=="
ArgumentError: invalid base64
from /usr/local/Cellar/ruby/2.6.1/lib/ruby/2.6.0/base64.rb:74:in `unpack1'
回答1:
Looks like this was a bug: https://github.com/dotnet/corefx/issues/30793 It's fixed in .NET Core but still present in .NET Framework up to 4.7.2.
This code should abort with exception instead of printing 1:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(Convert.FromBase64String("YWE==").Length);
}
}
Here's a test: https://dotnetfiddle.net/x2X9CT
来源:https://stackoverflow.com/questions/54852219/decoding-base64-in-c-sharp-sometimes-gives-incorrect-result-with-one-extra-paddi