00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #include "Base64.h"
00015
00016 const wxChar fillchar = '=';
00017
00018
00019
00020 static wxString cvt = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00021
00022
00023
00024 "abcdefghijklmnopqrstuvwxyz"
00025
00026
00027
00028 "0123456789+/");
00029
00030 wxString wxBase64::Encode(const wxUint8* pData, size_t len)
00031 {
00032 size_t c;
00033 wxString ret;
00034 ret.Alloc(len * 4 / 3 + len * 2 / 50);
00035 size_t resultLen = 0;
00036 wxString cr("\x00d\x00a");
00037
00038 for (size_t i = 0; i < len; ++i)
00039 {
00040 c = (pData[i] >> 2) & 0x3f;
00041 ret.Append(cvt[c], 1);
00042 if (++resultLen == 72) { ret += cr; resultLen = 0; }
00043 c = (pData[i] << 4) & 0x3f;
00044 if (++i < len)
00045 c |= (pData[i] >> 4) & 0x0f;
00046
00047 ret.Append(cvt[c], 1);
00048 if (++resultLen == 72) { ret += cr; resultLen = 0; }
00049 if (i < len)
00050 {
00051 c = (pData[i] << 2) & 0x3f;
00052 if (++i < len)
00053 c |= (pData[i] >> 6) & 0x03;
00054
00055 ret.Append(cvt[c], 1);
00056 }
00057 else
00058 {
00059 ++i;
00060 ret.Append(fillchar, 1);
00061 }
00062 if (++resultLen == 72) { ret += cr; resultLen = 0; }
00063
00064 if (i < len)
00065 {
00066 c = pData[i] & 0x3f;
00067 ret.Append(cvt[c], 1);
00068 }
00069 else
00070 {
00071 ret.Append(fillchar, 1);
00072 }
00073 if (++resultLen == 72) { ret += cr; resultLen = 0; }
00074 }
00075
00076 return ret;
00077 }
00078
00079 wxString wxBase64::Decode(const wxString& data)
00080 {
00081 int c;
00082 int c1;
00083 size_t len = data.Length();
00084 wxString ret;
00085 ret.Alloc(data.Length() * 3 / 4);
00086
00087 for (size_t i = 0; i < len; ++i)
00088 {
00089
00090 c = cvt.Find(data[i]);
00091 wxASSERT_MSG(c >= 0, _T("invalid base64 input"));
00092 ++i;
00093 c1 = cvt.Find(data[i]);
00094 wxASSERT_MSG(c1 >= 0, _T("invalid base64 input"));
00095 c = (c << 2) | ((c1 >> 4) & 0x3);
00096 ret.Append(c, 1);
00097 if (++i < len)
00098 {
00099 c = data[i];
00100 if (fillchar == c)
00101 break;
00102
00103 c = cvt.Find(c);
00104 wxASSERT_MSG(c >= 0, _T("invalid base64 input"));
00105 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
00106 ret.Append(c1, 1);
00107 }
00108
00109 if (++i < len)
00110 {
00111 c1 = data[i];
00112 if (fillchar == c1)
00113 break;
00114
00115 c1 = cvt.Find(c1);
00116 wxASSERT_MSG(c1 >= 0, _T("invalid base64 input"));
00117 c = ((c << 6) & 0xc0) | c1;
00118 ret.Append(c, 1);
00119 }
00120 }
00121
00122 return ret;
00123 }