Convert.FromBase64String()引发“无效的Base-64字符串”错误

aks*_*hay 1 c# base64 encode decode

我有一个使用Base64编码的密钥。

尝试解码时,我收到以下错误。错误被抛出byte[] todecode_byte = Convert.FromBase64String(data);

base64Decode中的错误输入不是有效的Base-64字符串,因为它包含非Base 64字符,两个以上的填充字符或填充字符中的非法字符。

我正在使用以下方法对此进行解码:

public string base64Decode(string data)
{
    try
    {
        System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
        System.Text.Decoder utf8Decode = encoder.GetDecoder();

        byte[] todecode_byte = Convert.FromBase64String(data); // this line throws the exception

        int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        string result = new String(decoded_char);
        return result;
    }
    catch (Exception e)
    {
        throw new Exception("Error in base64Decode" + e.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 7

因此,存在两个问题:

  1. 您的字符串不是4长整数的倍数。需要使用'='字符将其填充为4的倍数。
  2. 看起来这是用于URL的base 64格式,例如“ URL的修改Base64”。使用-代替+_代替/

因此,要解决这个问题,你需要换-+_/和填充它,就像这样:

public static byte[] DecodeUrlBase64(string s)
{
    s = s.Replace('-', '+').Replace('_', '/').PadRight(4*((s.Length+3)/4), '=');
    return Convert.FromBase64String(s);
}
Run Code Online (Sandbox Code Playgroud)