-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathQuotedPrintables.cs
116 lines (103 loc) · 5.23 KB
/
QuotedPrintables.cs
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Net.Imap4
{
internal class QuotedPrintables
{
public static string DecodeQuotedPrintables(string InputText)
{
var ResultChars = new List<char>();
Encoding encoding;
for (int i = 0; i < InputText.Length; i++)
{
var CurrentChar = InputText[i];
switch (CurrentChar)
{
case '=':
if ((i + 1) < InputText.Length && InputText[i + 1] == '?')
{
// Encoding
i += 2;
int StIndex = InputText.IndexOf('?', i);
int SubStringLength = StIndex - i;
string encodingName = InputText.Substring(i, SubStringLength);
encoding = Encoding.GetEncoding(encodingName);
i += SubStringLength + 1;
//Subencoding
StIndex = InputText.IndexOf('?', i);
SubStringLength = StIndex - i;
string SubEncoding = InputText.Substring(i, SubStringLength);
i += SubStringLength + 1;
//Text message
StIndex = InputText.IndexOf("?=", i);
SubStringLength = StIndex - i;
string Message = InputText.Substring(i, SubStringLength);
i += SubStringLength + 1;
// encoding
switch (SubEncoding)
{
case "B":
var base64EncodedBytes = Convert.FromBase64String(Message);
ResultChars.AddRange(encoding.GetString(base64EncodedBytes).ToCharArray());
// skip space #1
if ((i + 1) < InputText.Length && InputText[i + 1] == ' ')
{
i++;
}
break;
case "Q":
var CharByteList = new List<byte>();
for (int j = 0; j < Message.Length; j++)
{
var QChar = Message[j];
switch (QChar)
{
case '=':
j++;
string HexString = Message.Substring(j, 2);
byte CharByte = Convert.ToByte(HexString, 16);
CharByteList.Add(CharByte);
j += 1;
break;
default:
// Decode charbytes #1
if (CharByteList.Count > 0)
{
var CharString = encoding.GetString(CharByteList.ToArray());
ResultChars.AddRange(CharString.ToCharArray());
CharByteList.Clear();
}
ResultChars.Add(QChar);
break;
}
}
// Decode charbytes #2
if (CharByteList.Count > 0)
{
var CharString = encoding.GetString(CharByteList.ToArray());
ResultChars.AddRange(CharString.ToCharArray());
CharByteList.Clear();
}
// skip space #2
if ((i + 1) < InputText.Length && InputText[i + 1] == ' ')
{
i++;
}
break;
default:
throw new NotSupportedException($"Decode quoted printables: unsupported subencodeing: '{SubEncoding}'");
}
}
else
ResultChars.Add(CurrentChar);
break;
default:
ResultChars.Add(CurrentChar);
break;
}
}
return new string(ResultChars.ToArray());
}
}
}