【问题标题】:PHP base64_decode C# equivalentPHP base64_decode C# 等效
【发布时间】:2009-03-17 23:03:30
【问题描述】:

我正在尝试模仿执行以下操作的 php 脚本:

  1. 用 + 号替换 GET 变量的每个空格 ($var = preg_replace("/\s/","+",$_GET['var']); )
  2. 解码为base64:base64_decode($var);

第一次我添加了一个执行base64解码的方法:

        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);
            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);
        }
    }

但似乎 UTF-8 没有完成这项工作,所以我尝试了相同的方法,但使用的是 UTF-7

        public string base64Decode(string data)
    {
        try
        {
            System.Text.UTF7Encoding encoder = new System.Text.UTF7Encoding();

            System.Text.Decoder utf7Decode = encoder.GetDecoder();

            byte[] todecode_byte = Convert.FromBase64String(data);
            int charCount = utf7Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf7Decode.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);
        }
    }

最后说一句,成功的php解码包含特殊标志,如注册标志和商标标志,但C#版本没有!

另外,php base64_decode 是否受服务器语言影响?

【问题讨论】:

    标签: c# php base64


    【解决方案1】:

    UTF-7 不太可能是您想要的。你真的需要知道 PHP 使用的是什么编码。它可能使用您系统的默认编码。幸运的是,解码比您制作的要容易得多:

    public static string base64Decode(string data)
    {
        byte[] binary = Convert.FromBase64String(data);
        return Encoding.Default.GetString(binary);
    }
    

    没有必要明确地搞乱Encoder :)

    另一种可能是 PHP 使用的是 ISO Latin 1,即代码页 28591:

    public static string base64Decode(string data)
    {
        byte[] binary = Convert.FromBase64String(data);
        return Encoding.GetEncoding(28591).GetString(binary);
    }
    

    PHP 手册只是说:“在 PHP 6 之前,一个字符与一个字节相同。也就是说,可能有 256 个不同的字符。”遗憾的是它没有说明每个字节实际上是什么意味着...

    【讨论】:

    • 你拯救了我的一天!非常感谢!
    • Jon Skeet 你总是给人留下深刻印象。
    • 这个很简单。我最近的 hidebysig 回答需要更多的挖掘;)
    猜你喜欢
    • 2022-06-24
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2018-08-06
    相关资源
    最近更新 更多