我有一个使用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);
    }
}

最佳答案

因此,存在两个问题:


您的字符串不是4长整数的倍数。需要使用'='字符将其填充为4的倍数。
看起来是the format of base 64 used for URLs and suchlike, "modified Base64 for URL"。这使用-代替+_代替/


因此,要解决此问题,您需要将-交换为+,将_交换为/并填充它,如下所示:

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

09-20 21:16