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)
因此,存在两个问题:
-
代替+
和_
代替/
。因此,要解决这个问题,你需要换-
到+
和_
到/
和填充它,就像这样:
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)
归档时间: |
|
查看次数: |
7796 次 |
最近记录: |