3

私は次のことを行う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);
        }
    }

最後にもう1つ言いますが、成功したphpデコードには、登録記号や商標記号などの特別な記号が含まれていますが、C#バージョンには含まれていません。

また、php base64_decodeはサーバー言語の影響を受けますか?

4

1 に答える 1

10

UTF-7があなたが望むものになる可能性は非常に低いです。PHPが使用しているエンコーディングを本当に知る必要があります。システムのデフォルトのエンコーディングを使用している可能性があります。幸いなことに、作成するよりもデコードする方がはるかに簡単です。

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

明示的にいじる必要はありませんEncoder:)

もう1つの可能性は、PHPがコードページ28591であるISOLatin1を使用していることです。

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

PHPのマニュアルには、「PHP 6より前では、文字はバイトと同じです。つまり、正確に256の異なる文字が可能です」と書かれています。残念ながら、各バイトが実際に何を意味するのかはわかりません...

于 2009-03-17T23:09:19.203 に答える