Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对修改后的base64 URL进行解码/编码的代码_C#_Url_Base64_Encode_Decode - Fatal编程技术网

C# 对修改后的base64 URL进行解码/编码的代码

C# 对修改后的base64 URL进行解码/编码的代码,c#,url,base64,encode,decode,C#,Url,Base64,Encode,Decode,我想对数据进行base64编码,将其放入URL中,然后在HttpHandler中对其进行解码 我发现它允许使用“/”字符,这将破坏我的模板匹配。然后我发现维基百科中有一个“URL的修改Base64”的概念: URL变量存在一个修改的Base64,其中不使用填充“=”,标准Base64的“+”和“/”字符分别替换为“-”和“\”,因此不再需要使用URL编码器/解码器,也不会影响编码值的长度,保留相同的编码表单,以便在关系数据库、web表单和对象标识符中使用 使用.NET我想修改我当前的代码,从基本

我想对数据进行base64编码,将其放入URL中,然后在HttpHandler中对其进行解码

我发现它允许使用“/”字符,这将破坏我的模板匹配。然后我发现维基百科中有一个“URL的修改Base64”的概念:

URL变量存在一个修改的Base64,其中不使用填充“=”,标准Base64的“+”和“/”字符分别替换为“-”和“\”,因此不再需要使用URL编码器/解码器,也不会影响编码值的长度,保留相同的编码表单,以便在关系数据库、web表单和对象标识符中使用

使用.NET我想修改我当前的代码,从基本的base64编码和解码改为使用“modified base64 for URL”方法。有人这样做过吗

要解码,我知道它是从以下内容开始的:

string base64EncodedText = base64UrlEncodedText.Replace('-', '+').Replace('_', '/');

// Append '=' char(s) if necessary - how best to do this?

// My normal base64 decoding now uses encodedText
但是,我可能需要在末尾添加一两个“=”字符,这看起来有点复杂

我的编码逻辑应该简单一点:

// Perform normal base64 encoding
byte[] encodedBytes = Encoding.UTF8.GetBytes(unencodedText);
string base64EncodedText = Convert.ToBase64String(encodedBytes);

// Apply URL variant
string base64UrlEncodedText = base64EncodedText.Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');

我见过StackOverflow条目,但它的长度已知,因此它们可以硬编码结尾所需的等号数。

这应该可以正确地填充它:-

 base64 = base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '=');

还可以使用处理URL安全Base64编码和解码的UrlTokenEncode和UrlTokenDecode方法检查类HttpServerUtility

注意1:结果不是有效的Base64字符串。URL的某些不安全字符被替换。

///<summary>
/// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set.
///</summary>
///<param name="str">The origianl string</param>
///<returns>The Base64 encoded string</returns>
public static string Base64ForUrlEncode(string str)
{
    byte[] encbuff = Encoding.UTF8.GetBytes(str);
    return HttpServerUtility.UrlTokenEncode(encbuff);
}
///<summary>
/// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8.
///</summary>
///<param name="str">Base64 code</param>
///<returns>The decoded string.</returns>
public static string Base64ForUrlDecode(string str)
{
    byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
    return Encoding.UTF8.GetString(decbuff);
}
注2:结果与RFC4648中的base64url算法不同。

///<summary>
/// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set.
///</summary>
///<param name="str">The origianl string</param>
///<returns>The Base64 encoded string</returns>
public static string Base64ForUrlEncode(string str)
{
    byte[] encbuff = Encoding.UTF8.GetBytes(str);
    return HttpServerUtility.UrlTokenEncode(encbuff);
}
///<summary>
/// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8.
///</summary>
///<param name="str">Base64 code</param>
///<returns>The decoded string.</returns>
public static string Base64ForUrlDecode(string str)
{
    byte[] decbuff = HttpServerUtility.UrlTokenDecode(str);
    return Encoding.UTF8.GetString(decbuff);
}
///
///使用UTF-8字符集使用URL和文件名安全字母表进行Base 64编码。
///
///原始弦
///Base64编码字符串
公共静态字符串Base64ForUrlEncode(字符串str)
{
byte[]encbuff=Encoding.UTF8.GetBytes(str);
返回HttpServerUtility.UrlTokenEncode(encbuff);
}
///
///使用UTF-8解码带有URL和文件名安全字母表的Base64编码字符串。
///
///Base64代码
///解码的字符串。
公共静态字符串Base64ForUrlDecode(字符串str)
{
字节[]decbuff=HttpServerUtility.UrlTokenDecode(str);
返回Encoding.UTF8.GetString(decbuff);
}

我点击这里是为了寻找编码/解码base64url编码的代码,正如问题中所解释的,它与base64几乎没有什么不同


在此文档中找到c#代码段

没有足够的注释点,但如果有帮助,Sushil在提供的链接(JSON Web签名ietf草稿)中找到的代码片段在将Base 64编码为URL中的参数时适用

为那些懒惰的人复制了下面的代码段:

    static string Base64UrlEncode(byte[] arg)
    {
        string s = Convert.ToBase64String(arg); // Regular base64 encoder
        s = s.Split('=')[0]; // Remove any trailing '='s
        s = s.Replace('+', '-'); // 62nd char of encoding
        s = s.Replace('/', '_'); // 63rd char of encoding
        return s;
    }

    static byte[] Base64UrlDecode(string arg)
    {
        string s = arg;
        s = s.Replace('-', '+'); // 62nd char of encoding
        s = s.Replace('_', '/'); // 63rd char of encoding
        switch (s.Length % 4) // Pad with trailing '='s
        {
            case 0: break; // No pad chars in this case
            case 2: s += "=="; break; // Two pad chars
            case 3: s += "="; break; // One pad char
            default: throw new System.Exception(
              "Illegal base64url string!");
        }
        return Convert.FromBase64String(s); // Standard base64 decoder
    }

与公认的答案相比,下面是如何使用C#从根本上解码base64编码的url:

解码:

string codedValue = "base64encodedUrlHere";

string decoded;
byte[] buffer =  Convert.FromBase64String(codedValue);
decoded = Encoding.UTF8.GetString(buffer);

呸,你打了我。我会删除我的帖子,因为它看起来像是我复制了你:)这个加起来不是三个“=”字符吗?看起来只有0、1或2个字符。@Kirk:如果添加3个字符,则base64字符串已经损坏。我想验证字符串是个好主意,它应该只包含预期的字符和长度%4!=3.Hmmm。在尝试这一点时,它并没有起到作用。仍然在寻找答案。等号的数目不能正确平移。@AnthonyWJones'它应该只包含预期的字符和长度%4!=1',对吗?你的提示是一个多小时的、一毛不拔的寻找答案的光荣结局。谢谢对每个/+和=,不是都使用%编码吗?这不如另一个答案有效否,它用数字替换结尾填充的等号,用减号和下划线替换加号和斜杠。请注意,
urltokencode
不是严格意义上的,因为它用“0”替换“=”填充,“1”或“2”取决于它替换了多少个等号。这是我在GMail API v1(message.Raw)中解析邮件时唯一有效的解决方案。如果您提供更多详细信息并与接受的答案进行比较,您可能会得到一个向上的投票-thanksIt不是base64编码的URL,但是base64url编码的数据。这与Xamarin兼容,因为它不使用System.web正是我要找的!对于Xamarin来说,这是一个非常好的选择,无需使用库。