用于.NET的IMAP文件夹路径编码(IMAP UTF-7)?

时间:2009-02-20 13:20:02

标签: .net encoding imap utf-7

IMAP规范(RFC 2060,5.1.3。邮箱国际命名约定)介绍了如何处理文件夹名称中的非ASCII字符。它定义了修改后的 UTF-7编码:

  

按惯例,国际邮箱   使用a指定名称   修改版的UTF-7编码   在[UTF-7]中描述。目的   这些修改是纠正的   UTF-7存在以下问题:

     
      
  1. UTF-7使用“+”字符进行移位;这与之相冲突   邮箱名称中常用的“+”,特别是USENET   新闻组名称。

  2.   
  3. UTF-7的编码是BASE64,使用“/”字符;这个   与使用“/”作为流行的层次结构分隔符冲突。

  4.   
  5. UTF-7禁止未编码使用“\”;这与之相冲突        使用“\”作为流行的层次结构分隔符。

  6.   
  7. UTF-7禁止未编码使用“〜”;这与之相冲突        在某些服务器中使用“〜”作为主目录指示符。

  8.   
  9. UTF-7允许多个替代形式表示相同的形式        串;特别是,可打印的US-ASCII字符可以        以编码形式表示。

  10.         

    在修改后的UTF-7中,可打印的US-ASCII字符除“&”外代表自己;   也就是说,八位字节值为0x20-0x25的字符   和0x27-0x7e。字符“&”   (0x26)由两个八位字节序列“& - ”表示。

         

    所有其他字符(八位字节值   表示0x00-0x1f,0x7f-0xff和所有Unicode 16位八位字节   在改进的BASE64中,还有一个   从[UTF-7]修改“,”是   用而不是“/”   修改后的BASE64绝不能用于表示   任何打印US-ASCII字符   这可以代表自己。

         

    “&安培;”用于转移到修改   BASE64和“ - ”转回US-ASCII。所有名称均以US-ASCII开头,   并且必须以US-ASCII结尾(即,   以16位Unicode结尾的名称   八位组必须以“ - ”结尾。

在我开始实现它之前,我的问题是:那里有一些 .NET代码/库(甚至在框架中)吗?我找不到.NET资源(只有implementations for other languages/frameworks)。

谢谢!

3 个答案:

答案 0 :(得分:2)

这太专业化,不能出现在框架中。虽然许多不完整的“实现”在我看来根本没有对转换感到麻烦,但很乐意将所有非us-ascii字符传递给IMAP服务器。

但是我过去实现了它,它实际上只有30行代码。你遍历字符串中的所有字符并输出它们,如果它们落在0x20和0x7e之间的范围内(不要忘记在“&”之后附加“ - ”)否则收集所有非us-ascii并使用它们转换它们UTF7(或UTF8 + base64,我不太确定)将“/”替换为“,”。此外,您需要保持“移位状态”,例如你是否正在编码非us-ascii或输出us-ascii并附加过渡令牌“&”和“ - ”关于国家改变。

答案 1 :(得分:0)

未经测试,但如果应用了this的错误修正,则Aleksey的MIT许可代码看起来不错:

    /// <summary>
    /// Takes a UTF-16 encoded string and encodes it as modified UTF-7.
    /// </summary>
    /// <param name="s">The string to encode.</param>
    /// <returns>A UTF-7 encoded string</returns>
    /// <remarks>IMAP uses a modified version of UTF-7 for encoding international mailbox names. For
    /// details, refer to RFC 3501 section 5.1.3 (Mailbox International Naming Convention).</remarks>
    internal static string UTF7Encode(string s) {
        StringReader reader = new StringReader(s);
        StringBuilder builder = new StringBuilder();
        while (reader.Peek() != -1) {
            char c = (char)reader.Read();
            int codepoint = Convert.ToInt32(c);
            // It's a printable ASCII character.
            if (codepoint > 0x1F && codepoint < 0x7F) {
                builder.Append(c == '&' ? "&-" : c.ToString());
            } else {
                // The character sequence needs to be encoded.
                StringBuilder sequence = new StringBuilder(c.ToString());
                while (reader.Peek() != -1) {
                    codepoint = Convert.ToInt32((char)reader.Peek());
                    if (codepoint > 0x1F && codepoint < 0x7F)
                        break;
                    sequence.Append((char)reader.Read());
                }
                byte[] buffer = Encoding.BigEndianUnicode.GetBytes(
                    sequence.ToString());
                string encoded = Convert.ToBase64String(buffer).Replace('/', ',').
                    TrimEnd('=');
                builder.Append("&" + encoded + "-");
            }
        }
        return builder.ToString();
    }

    /// <summary>
    /// Takes a modified UTF-7 encoded string and decodes it.
    /// </summary>
    /// <param name="s">The UTF-7 encoded string to decode.</param>
    /// <returns>A UTF-16 encoded "standard" C# string</returns>
    /// <exception cref="FormatException">The input string is not a properly UTF-7 encoded
    /// string.</exception>
    /// <remarks>IMAP uses a modified version of UTF-7 for encoding international mailbox names. For
    /// details, refer to RFC 3501 section 5.1.3 (Mailbox International Naming Convention).</remarks>
    internal static string UTF7Decode(string s) {
        StringReader reader = new StringReader(s);
        StringBuilder builder = new StringBuilder();
        while (reader.Peek() != -1) {
            char c = (char)reader.Read();
            if (c == '&' && reader.Peek() != '-') {
                // The character sequence needs to be decoded.
                StringBuilder sequence = new StringBuilder();
                while (reader.Peek() != -1) {
                    if ((c = (char)reader.Read()) == '-')
                        break;
                    sequence.Append(c);
                }
                string encoded = sequence.ToString().Replace(',', '/');
                int pad = encoded.Length % 4;
                if (pad > 0)
                    encoded = encoded.PadRight(encoded.Length + (4 - pad), '=');
                try {
                    byte[] buffer = Convert.FromBase64String(encoded);
                    builder.Append(Encoding.BigEndianUnicode.GetString(buffer));
                } catch (Exception e) {
                    throw new FormatException(
                        "The input string is not in the correct Format.", e);
                }
            } else {
                if (c == '&' && reader.Peek() == '-')
                    reader.Read();
                builder.Append(c);
            }
        }
        return builder.ToString();
    }

在当前状态下不使用this代码,它包含[...] UTF7.GetBytes([...]) [...] .Replace('+', '&')-它使用现有的.Net UTF-7编码例程,并且(其中包括)将+替换为结果中的&。这是错误,因为它不仅将“移位字符”从+更改为&(有意且正确),而且还将所有+个字符在以base64编码的区域内(不得更改为&)。

答案 2 :(得分:0)

//
// ImapEncoding.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2019 Microsoft Corp. (www.microsoft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System.Text;

namespace MailKit.Net.Imap {
    static class ImapEncoding
    {
        const string utf7_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";

        static readonly byte[] utf7_rank = {
            255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
            255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
            255,255,255,255,255,255,255,255,255,255,255, 62, 63,255,255,255,
             52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,255,255,255,
            255,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
             15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255,
            255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
             41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255,
        };

        public static string Decode (string text)
        {
            var decoded = new StringBuilder ();
            bool shifted = false;
            int bits = 0, v = 0;
            int index = 0;
            char c;

            while (index < text.Length) {
                c = text[index++];

                if (shifted) {
                    if (c == '-') {
                        // shifted back out of modified UTF-7
                        shifted = false;
                        bits = v = 0;
                    } else if (c > 127) {
                        // invalid UTF-7
                        return text;
                    } else {
                        byte rank = utf7_rank[(byte) c];

                        if (rank == 0xff) {
                            // invalid UTF-7
                            return text;
                        }

                        v = (v << 6) | rank;
                        bits += 6;

                        if (bits >= 16) {
                            char u = (char) ((v >> (bits - 16)) & 0xffff);
                            decoded.Append (u);
                            bits -= 16;
                        }
                    }
                } else if (c == '&' && index < text.Length) {
                    if (text[index] == '-') {
                        decoded.Append ('&');
                        index++;
                    } else {
                        // shifted into modified UTF-7
                        shifted = true;
                    }
                } else {
                    decoded.Append (c);
                }
            }

            return decoded.ToString ();
        }

        static void Utf7ShiftOut (StringBuilder output, int u, int bits)
        {
            if (bits > 0) {
                int x = (u << (6 - bits)) & 0x3f;
                output.Append (utf7_alphabet[x]);
            }

            output.Append ('-');
        }

        public static string Encode (string text)
        {
            var encoded = new StringBuilder ();
            bool shifted = false;
            int bits = 0, u = 0;

            for (int index = 0; index < text.Length; index++) {
                char c = text[index];

                if (c >= 0x20 && c < 0x7f) {
                    // characters with octet values 0x20-0x25 and 0x27-0x7e
                    // represent themselves while 0x26 ("&") is represented
                    // by the two-octet sequence "&-"

                    if (shifted) {
                        Utf7ShiftOut (encoded, u, bits);
                        shifted = false;
                        bits = 0;
                    }

                    if (c == 0x26)
                        encoded.Append ("&-");
                    else
                        encoded.Append (c);
                } else {
                    // base64 encode
                    if (!shifted) {
                        encoded.Append ('&');
                        shifted = true;
                    }

                    u = (u << 16) | (c & 0xffff);
                    bits += 16;

                    while (bits >= 6) {
                        int x = (u >> (bits - 6)) & 0x3f;
                        encoded.Append (utf7_alphabet[x]);
                        bits -= 6;
                    }
                }
            }

            if (shifted)
                Utf7ShiftOut (encoded, u, bits);

            return encoded.ToString ();
        }
    }
}