Convert.FromBase64String 给出 "The input is not a valid Base-64 string" 的错误

Convert.FromBase64String gives the error of "The input is not a valid Base-64 string"

这是我的字符串,我尝试将其从 base64 转换为人类可读的字符串:

eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0

它适用于从 base64 转换的在线站点,例如 this site

在 c# .net6 上我尝试了这个代码:

var bytes = Convert.FromBase64String(base64payload);

上面的字符串是哪个base64payload。 为什么我在 c# dotnet 6 上会收到此错误?

"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."

据我所知,( a-z A-Z 0-9 / +) 是有效的,我的眼睛在这个字符串中没有看到任何错误的 base64 字符 + 它适用于其他地方。

您的字符串缺少一些填充。您可以检查 here 并根据需要进行修复。

修复后正确的字符串是:

eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0=

之后,使用以下代码:

using System;
using System.Text;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var coded = ("eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9kYXRlb2ZiaXJ0aCI6IjIvMjUvMTk5MSAxMjowMDowMCBBTSIsIm5iZiI6MTY0MTQwNjk2MCwiZXhwIjoxNjQxNDEwNTYwLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo3MDAwLyIsImF1ZCI6Imh0dHBzOi8vbG9jYWxob3N0OjcwMDAvIn0=");
            string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(coded));
            Console.WriteLine(inputStr);

        }
    }