【问题标题】:Why do we need to first convert to bytes then string when specifically decoding base64string?为什么我们在专门解码base64string时需要先转换为字节然后再转换为字符串?
【发布时间】:2018-07-18 11:57:48
【问题描述】:

考虑以下方法:

private (string email, string password) GetCredentials()
    {

        string head = Request.Headers["Authorization"];
        if (head == null || !head.StartsWith("Basic ")) throw new TokenValidationException("Token absent.");

        AuthenticationHeaderValue authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);

        if (!authHeader.Scheme.Equals("Basic")) throw new AuthenticationException();

        var bytes = Convert.FromBase64String(authHeader.Parameter);
        var header = System.Text.Encoding.UTF8.GetString(bytes);

        var parts = header.Split(new[] { ':' }, 2);
        return (parts[0].ToLowerInvariant(), parts[1]);
    }

为什么我们需要先获取字节,然后将它们解码为 UTF8 字符串?

【问题讨论】:

  • 到 UTF8 字符串? 不,来自 UTF8 字符串
  • 一个 Base64 字符串代表编码字节,这些字节可以来自任何东西 - 字符串、图像、音频文件、可执行文件等。当你解码时,你会得到字节,然后由你决定来决定如何进一步解释它们。

标签: c# asp.net .net asp.net-web-api


【解决方案1】:

因为您可以将 任何 BLOB 存储为 base-64 - 它不需要是字符串。它可以是 protobuf 有效负载、图像、文件附件等。事实上,通常当您使用 base-64 时,因为您希望将二进制有效负载存储在文本协议中;如果您只想存储string,您只需...直接嵌入字符串。所以:几乎从来没有实际上是一个字符串有效负载,因此为什么没有 DecodeBase64ThenDecodeThatAsString 方法。

【讨论】:

    猜你喜欢
    • 2019-10-16
    • 2011-06-27
    • 2019-10-10
    • 2011-12-18
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    相关资源
    最近更新 更多