【问题标题】:Convert.FromBase64String() throws "invalid Base-64 string" errorConvert.FromBase64String() 抛出“无效的 Base-64 字符串”错误
【发布时间】:2018-05-25 08:21:22
【问题描述】:

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

【问题讨论】:

  • 请张贴您要解码的字符串(如果不是太大)。
  • 抛出什么异常,从哪里抛出?
  • 如果它很大,请使用 PasteBin
  • 该错误似乎表明您的输入错误。您检查过输入的字符串是否正确吗?
  • - 不是有效字符。你的字符串是从哪里来的?您可能需要将- 字符更改为+/。此外,它的长度必须是 4 个字符的倍数。除非我数错,否则您的字符串有 43 个字符。

标签: c# base64 decode encode


【解决方案1】:

所以有两个问题:

  1. 您的字符串不是 4 的倍数。需要使用 '=' 字符将其填充为 4 的倍数。
  2. 好像是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);
}

【讨论】:

    【解决方案2】:

    我在使用 .Net 5 Identity Framework 时在 ASP.Net MVC 应用程序中发送密码重置令牌时遇到了同样的问题。 URL 中的重置密码令牌是有效的 URL 编码 Base64 字符串,但在绑定查询参数时,.Net Framework 通过将 + 符号转换为空格来产生问题。因此,在用 + 号替换空格后,它工作得很好。

    我已经根据@Mathew Watson 接受的答案更新了 DecodeUrlBase64 方法来处理空格。

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

    【讨论】:

      【解决方案3】:

      您的 base64 字符串无效。它包含一个不允许的-

      static void Main()
      {
          string tmp = "eL78WIArGQ7bC44Ozr0yvUBkz9oc5YlsENYJilInSP==";
          byte[] tmp2 = Convert.FromBase64String(tmp);
      }
      

      -> 删除减号 -> 添加了两个填充字符“=

      【讨论】:

      • 这行得通。所以这意味着我使用的输入字符串不正确。谢谢。
      • 你不能只去掉减号!你正在改变结果。您需要将其替换为正确的字符。
      • 对。此示例正在运行,但结果发生了变化
      • 我只想展示问题。我相信每个人都知道,如果您忽略某些字节,则无法解释二进制数据;)。 @akshay:无论如何 - 得到一些正确的输入
      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多