| 239 | } |
| 240 | |
| 241 | string EncodeBase64(const unsigned char* pch, size_t len) { |
| 242 | static const char* pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 243 | |
| 244 | string strRet = ""; |
| 245 | strRet.reserve((len + 2) / 3 * 4); |
| 246 | |
| 247 | int mode = 0, left = 0; |
| 248 | const unsigned char* pchEnd = pch + len; |
| 249 | |
| 250 | while (pch < pchEnd) { |
| 251 | int enc = *(pch++); |
| 252 | switch (mode) { |
| 253 | case 0: // we have no bits |
| 254 | strRet += pbase64[enc >> 2]; |
| 255 | left = (enc & 3) << 4; |
| 256 | mode = 1; |
| 257 | break; |
| 258 | |
| 259 | case 1: // we have two bits |
| 260 | strRet += pbase64[left | (enc >> 4)]; |
| 261 | left = (enc & 15) << 2; |
| 262 | mode = 2; |
| 263 | break; |
| 264 | |
| 265 | case 2: // we have four bits |
| 266 | strRet += pbase64[left | (enc >> 6)]; |
| 267 | strRet += pbase64[enc & 63]; |
| 268 | mode = 0; |
| 269 | break; |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | if (mode) { |
| 274 | strRet += pbase64[left]; |
| 275 | strRet += '='; |
| 276 | if (mode == 1) strRet += '='; |
| 277 | } |
| 278 | |
| 279 | return strRet; |
| 280 | } |
| 281 | |
| 282 | string EncodeBase64(const string& str) { |
| 283 | return EncodeBase64((const unsigned char*)str.c_str(), str.size()); |