C# Convert.FromBase64String()抛出;无效的Base-64字符串“;错误
我有一个密钥是Base64编码的 在尝试解码时,我收到以下错误。该错误由C# Convert.FromBase64String()抛出;无效的Base-64字符串“;错误,c#,base64,decode,encode,C#,Base64,Decode,Encode,我有一个密钥是Base64编码的 在尝试解码时,我收到以下错误。该错误由byte[]todecode\u byte=Convert.FromBase64String(数据)引发 Base64Decode中出错输入不是有效的Base-64字符串,因为它包含非Base 64字符、两个以上的填充字符或填充字符中的非法字符 我正在使用以下方法来解码: public string base64Decode(string data) { try { System.Text.U
byte[]todecode\u byte=Convert.FromBase64String(数据)引发代码>
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);
}
}
您的base64字符串无效。它包含一个不允许的-
static void Main()
{
string tmp = "eL78WIArGQ7bC44Ozr0yvUBkz9oc5YlsENYJilInSP==";
byte[] tmp2 = Convert.FromBase64String(tmp);
}
->减去
->添加了两个填充字符“=
”,因此存在两个问题:
您的字符串长度不是4的倍数。需要使用“=”字符将其填充为4的倍数
它看起来像是一个。这将使用-
而不是+
和
而不是/
因此,要解决此问题,您需要将-
交换到+
,将-
交换到/
并将其填充,如下所示:
public static byte[] DecodeUrlBase64(string s)
{
s = s.Replace('-', '+').Replace('_', '/').PadRight(4*((s.Length+3)/4), '=');
return Convert.FromBase64String(s);
}
请发布您试图解码的字符串(如果不是太大)。引发了什么异常以及从何处引发异常?如果是巨大的,请使用。错误似乎表明您的输入错误。是否已检查输入字符串是否正确?-
不是有效字符。你的绳子是从哪里来的?您可能需要将-
字符更改为+
或/
。此外,它必须是4个字符长的倍数。除非我算错了,否则你的字符串有43个字符。这很有效。这意味着我使用的输入字符串不正确。谢谢。你不能只去掉负号!你正在改变结果。你需要用正确的字符替换它。对。此示例正在运行,但正在更改结果。我只想显示问题。我相信每个人都知道,如果忽略一些字节,二进制数据的解释是不可能的;)@akshay:不管怎样-获得一些正确的输入